#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "employeedialog.h"
#include "toydialog.h"
#include "processdialog.h"
#include "passworddialog.h"
#include "systemsettingsdialog.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDate>
#include <QMessageBox>
#include <QSqlTableModel>
#include <QFileDialog>
#include <QTextDocument>
#include <QtPrintSupport/QPrinter>
#include <QtPrintSupport/QPrintDialog>
#include <QtPrintSupport/QPrintPreviewDialog>
#include <QTextStream>
#include <QFile>
#include <QProcess>
#include <QTableWidgetItem>
#include <QComboBox>
#include <QTimer>
#include <QSettings>
#include <QStandardPaths>
#include <QDir>
#include <QApplication>
#include <QDesktopWidget>
#include <QScreen>
#include <QHeaderView>
#include <QScrollBar>
#include <QScrollBar>
#include <QDebug>
#include <QInputDialog>
#include <QHeaderView>
#include <QComboBox>
#include <QPushButton>
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QPixmap>
#include <Qt>
#include <QTimer>
#include <QTimer>

// 辅助函数：执行SQL查询并处理错误
bool executeQuery(QSqlQuery &query, const QString &errorContext, QWidget *parent = nullptr)
{
    qDebug() << "执行SQL查询:" << query.lastQuery();
    
    if (!query.exec()) {
        QString errorMsg = QString("%1\n错误信息：%2\nSQL语句：%3")
            .arg(errorContext)
            .arg(query.lastError().text())
            .arg(query.lastQuery());
        qDebug() << "SQL执行失败:" << errorMsg;
        QMessageBox::critical(parent, "数据库错误", errorMsg);
        return false;
    }
    
    qDebug() << "SQL查询执行成功";
    return true;
}

// 辅助函数：开始数据库事务
bool beginTransaction(QSqlDatabase &database, const QString &errorContext, QWidget *parent = nullptr)
{
    if (!database.transaction()) {
        QString errorMsg = QString("%1\n错误信息：%2")
            .arg(errorContext)
            .arg(database.lastError().text());
        QMessageBox::critical(parent, "事务错误", errorMsg);
        return false;
    }
    return true;
}

// 全局数据库连接
QSqlDatabase db;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , currentEmployeePage(0)
    , currentToyPage(0)
    , currentDeptPage(0)
    , currentProductionPage(0)
    , currentProcessPage(0)
    , itemsPerPage(20) // 默认每页显示20条记录
    , currentRecentActivityPage(0)
    , totalRecentActivityPages(0)
    , totalEmployeeRecords(0)
    , totalToyRecords(0)
    , totalDeptRecords(0)
    , totalProcessRecords(0)
    // 数据查询页面分页相关变量
    , currentDailyReportPage(0)
    , totalDailyReportRecords(0)
    , currentMonthlyReportPage(0)
    , totalMonthlyReportRecords(0)
    , currentFactoryStatsPage(0)
    , totalFactoryStatsRecords(0)
{
    qDebug() << "主窗口构造函数开始";
    ui->setupUi(this);
    
    qDebug() << "UI设置完成";

    // 初始化分页控件成员变量
    // 最近生产记录分页控件
    pushButton_firstPageRecentActivity = ui->pushButton_firstPageRecentActivity;
    pushButton_prevPageRecentActivity = ui->pushButton_prevPageRecentActivity;
    pushButton_nextPageRecentActivity = ui->pushButton_nextPageRecentActivity;
    pushButton_lastPageRecentActivity = ui->pushButton_lastPageRecentActivity;
    label_pageInfoRecentActivity = ui->label_pageInfoRecentActivity;
    
    // 员工管理分页控件
    pushButton_firstPageEmployee = ui->pushButton_firstPageEmployee;
    pushButton_prevPageEmployee = ui->pushButton_prevPageEmployee;
    pushButton_nextPageEmployee = ui->pushButton_nextPageEmployee;
    pushButton_lastPageEmployee = ui->pushButton_lastPageEmployee;
    label_pageInfoEmployee = ui->label_pageInfoEmployee;
    
    // 产品管理分页控件
    pushButton_firstPageProduct = ui->pushButton_firstPageProduct;
    pushButton_prevPageProduct = ui->pushButton_prevPageProduct;
    pushButton_nextPageProduct = ui->pushButton_nextPageProduct;
    pushButton_lastPageProduct = ui->pushButton_lastPageProduct;
    label_pageInfoProduct = ui->label_pageInfoProduct;
    
    // 班组管理分页控件
    pushButton_firstPageDepartment = ui->pushButton_firstPageDepartment;
    pushButton_prevPageDepartment = ui->pushButton_prevPageDepartment;
    pushButton_nextPageDepartment = ui->pushButton_nextPageDepartment;
    pushButton_lastPageDepartment = ui->pushButton_lastPageDepartment;
    label_pageInfoDepartment = ui->label_pageInfoDepartment;
    
    // 工序管理分页控件（在UI中动态创建，不直接赋值）
    pushButton_firstPageProcess = nullptr;
    pushButton_prevPageProcess = nullptr;
    pushButton_nextPageProcess = nullptr;
    pushButton_lastPageProcess = nullptr;
    label_pageInfoProcess = nullptr;
    
    // 员工日报表分页控件
    pushButton_firstPageDailyReport = ui->pushButton_firstPageDailyReport;
    pushButton_prevPageDailyReport = ui->pushButton_prevPageDailyReport;
    pushButton_nextPageDailyReport = ui->pushButton_nextPageDailyReport;
    pushButton_lastPageDailyReport = ui->pushButton_lastPageDailyReport;
    label_pageInfoDailyReport = ui->label_pageInfoDailyReport;
    
    // 员工月报表分页控件
    pushButton_firstPageMonthlyReport = ui->pushButton_firstPageMonthlyReport;
    pushButton_prevPageMonthlyReport = ui->pushButton_prevPageMonthlyReport;
    pushButton_nextPageMonthlyReport = ui->pushButton_nextPageMonthlyReport;
    pushButton_lastPageMonthlyReport = ui->pushButton_lastPageMonthlyReport;
    label_pageInfoMonthlyReport = ui->label_pageInfoMonthlyReport;
    
    // 全厂/班组产量统计分页控件
    pushButton_firstPageFactoryStats = ui->pushButton_firstPageFactoryStats;
    pushButton_prevPageFactoryStats = ui->pushButton_prevPageFactoryStats;
    pushButton_nextPageFactoryStats = ui->pushButton_nextPageFactoryStats;
    pushButton_lastPageFactoryStats = ui->pushButton_lastPageFactoryStats;
    label_pageInfoFactoryStats = ui->label_pageInfoFactoryStats;

    // 设置窗口图标，添加错误处理
    QIcon appIcon(":/favicon.ico");
    if (appIcon.isNull()) {
        qDebug() << "资源中的图标加载失败，尝试从文件系统加载";
        // 如果资源中的图标加载失败，尝试从文件系统加载
        appIcon = QIcon("favicon.ico");
        
        // 如果文件系统中的图标也加载失败，使用默认图标
        if (appIcon.isNull()) {
            // 创建一个简单的默认图标
            QPixmap pixmap(32, 32);
            pixmap.fill(Qt::blue);
            appIcon = QIcon(pixmap);
            qDebug() << "文件系统图标加载失败，使用默认图标";
        }
    }
    
    if (!appIcon.isNull()) {
        setWindowIcon(appIcon);
        qDebug() << "窗口图标设置成功";
    } else {
        qDebug() << "无法加载窗口图标";
    }

    // 初始化分页参数
    currentEmployeePage = 0;
    currentToyPage = 0;
    currentDeptPage = 0;
    currentProductionPage = 0;
    itemsPerPage = 20;

    // 初始化数据库
    qDebug() << "开始初始化数据库";
    if (!initDatabase()) {
        QString errorMsg = QString::fromLocal8Bit("数据库初始化失败，程序可能无法正常运行！\n请检查数据库文件权限或重新安装程序。");
        QMessageBox::critical(this, QString::fromLocal8Bit("系统错误"), errorMsg);
        qCritical() << errorMsg;
        // 不再直接退出程序，而是显示错误但允许用户看到错误信息
        // 只禁用需要数据库的功能，保留基本界面
        statusBar()->showMessage(QString::fromLocal8Bit("数据库连接失败，部分功能不可用"), 10000);
    } else {
        qDebug() << "数据库初始化完成";

        // 初始化UI组件
        qDebug() << "开始初始化UI";
        initUI();
        qDebug() << "UI初始化完成";

        // 初始化工序管理界面 - 新增
        qDebug() << "开始初始化工序管理界面";
        setupProcessManagementUI();
        qDebug() << "工序管理界面初始化完成";

        // 连接信号和槽
        qDebug() << "开始连接信号和槽";
        connectSignalsAndSlots();
        qDebug() << "信号和槽连接完成";

        // 加载初始数据
        qDebug() << "开始加载初始数据";
        loadInitialData();
        qDebug() << "初始数据加载完成";

        // 更新仪表盘
        qDebug() << "开始更新仪表盘";
        updateDashboard();
        qDebug() << "仪表盘更新完成";
    }

    // 显示当前日期（这部分不依赖数据库）
    qDebug() << "设置日期控件";
    ui->dateEdit_entryDate->setDate(QDate::currentDate());
    ui->dateEdit_startDate->setDate(QDate::currentDate().addDays(-30));
    ui->dateEdit_endDate->setDate(QDate::currentDate());
    ui->dateEdit_month->setDate(QDate::currentDate());
    ui->dateEdit_wageMonth->setDate(QDate::currentDate());

    // 初始化样式
    qDebug() << "开始初始化样式";
    initStyles();
    qDebug() << "样式初始化完成";
    
    qDebug() << "主窗口初始化完成";
}

MainWindow::~MainWindow()
{
    delete ui;
}

// 初始化数据库
bool MainWindow::initDatabase()
{
    // 添加SQLite数据库连接
    db = QSqlDatabase::addDatabase("QSQLITE");
    
    // 使用相对路径存储数据库文件，避免硬编码绝对路径
    QString dbPath = "toy_factory.db";
    db.setDatabaseName(dbPath);
    
    qDebug() << "尝试打开数据库，路径：" << dbPath;
    qDebug() << "当前工作目录：" << QDir::currentPath();
    qDebug() << "数据库文件是否存在：" << QFile::exists(dbPath);

    // 检查数据库文件是否存在，如果不存在则创建
    if (!QFile::exists(dbPath)) {
        qDebug() << "数据库文件不存在，将创建新数据库";
        // 创建空的数据库文件
        QFile dbFile(dbPath);
        if (!dbFile.open(QIODevice::WriteOnly)) {
            QString errorMsg = QString("无法创建数据库文件: %1\n错误信息: %2")
                .arg(dbPath)
                .arg(dbFile.errorString());
            QMessageBox::critical(this, "数据库错误", errorMsg);
            qCritical() << errorMsg;
            return false;
        }
        dbFile.close();
    }

    // 打开数据库
    if (!db.open()) {
        QString errorMsg = QString("无法打开数据库: %1\n数据库文件路径: %2\n工作目录: %3\n文件存在: %4")
            .arg(db.lastError().text())
            .arg(dbPath)
            .arg(QDir::currentPath())
            .arg(QFile::exists(dbPath) ? "是" : "否");
        QMessageBox::critical(this, "数据库错误", errorMsg);
        qCritical() << errorMsg;
        return false;
    }
    
    qDebug() << "数据库打开成功";
    qDebug() << "数据库驱动：" << db.driverName();
    qDebug() << "数据库连接名：" << db.connectionName();

    // 创建所需的表
    if (!createTables()) {
        QString errorMsg = "创建数据表失败，程序可能无法正常运行！";
        QMessageBox::critical(this, "数据库错误", errorMsg);
        qCritical() << errorMsg;
        return false;
    }
    
    qDebug() << "数据表创建完成";

    // 加载模拟数据
    if (!loadMockData()) {
        QString warnMsg = "加载模拟数据时出现问题，但程序仍可继续运行";
        QMessageBox::warning(this, "数据加载警告", warnMsg);
        qWarning() << warnMsg;
        // 这里不返回false，因为即使模拟数据加载失败，程序仍然可以继续运行
    }
    
    qDebug() << "数据库初始化完成";

    return true;
}

// 创建数据库表
bool MainWindow::createTables()
{
    QSqlQuery query;

    // 开始事务
    if (!beginTransaction(db, "创建数据表时开启事务失败", this)) {
        return false;
    }

    // 创建员工表
    // 字段说明：
    // id: 员工ID，主键，自增
    // employee_id: 员工编号，唯一标识
    // name: 员工姓名
    // team: 所属班组
    // hire_date: 入职日期
    // contact: 联系方式
    // status: 员工状态，默认'在职'
    QString createEmployeeTable = "CREATE TABLE IF NOT EXISTS employees ("
               "id INTEGER PRIMARY KEY AUTOINCREMENT, "
               "employee_id TEXT UNIQUE NOT NULL, "
               "name TEXT NOT NULL, "
               "team TEXT, "
               "hire_date TEXT, "
               "contact TEXT, "
               "status TEXT DEFAULT '在职')";
    query.prepare(createEmployeeTable);
    if (!executeQuery(query, "创建员工表失败", this)) {
        db.rollback();
        return false;
    }

    // 创建玩具产品表
    // 字段说明：
    // id: 玩具ID，主键，自增
    // toy_id: 玩具编号，唯一标识
    // name: 玩具名称
    // description: 玩具描述
    // piece_rate: 计件单价
    // effective_date: 生效日期，默认当前日期
    QString createToysTable = "CREATE TABLE IF NOT EXISTS toys ("
               "id INTEGER PRIMARY KEY AUTOINCREMENT, "
               "toy_id TEXT UNIQUE NOT NULL, "
               "name TEXT NOT NULL, "
               "description TEXT, "
               "piece_rate REAL NOT NULL, "
               "effective_date TEXT DEFAULT CURRENT_DATE)";
    query.prepare(createToysTable);
    if (!executeQuery(query, "创建玩具表失败", this)) {
        db.rollback();
        return false;
    }

    // 创建生产记录表
    // 字段说明：
    // id: 生产记录ID，主键，自增
    // date: 生产日期
    // employee_id: 员工ID，外键
    // toy_id: 玩具ID，外键
    // quantity: 生产数量
    QString createProductionTable = "CREATE TABLE IF NOT EXISTS production ("
               "id INTEGER PRIMARY KEY AUTOINCREMENT, "
               "date TEXT NOT NULL, "
               "employee_id INTEGER NOT NULL, "
               "toy_id INTEGER NOT NULL, "
               "quantity INTEGER NOT NULL, "
               "FOREIGN KEY (employee_id) REFERENCES employees(id), "
               "FOREIGN KEY (toy_id) REFERENCES toys(id), "
               "UNIQUE(date, employee_id, toy_id))";
    query.prepare(createProductionTable);
    if (!executeQuery(query, "创建生产记录表失败", this)) {
        db.rollback();
        return false;
    }

    // 创建新的生产记录表（支持工序维度） - 新增
    // 字段说明：
    // id: 生产记录ID，主键，自增
    // date: 生产日期
    // employee_id: 员工ID，外键
    // toy_id: 玩具ID，外键
    // process_id: 工序ID，外键
    // quantity: 生产数量
    // piece_rate: 计件单价
    // subtotal: 小计金额
    // notes: 备注
    // created_at: 创建时间，默认当前时间戳
    // updated_at: 更新时间，默认当前时间戳
    QString createProductionV2Table = "CREATE TABLE IF NOT EXISTS production_v2 ("
               "id INTEGER PRIMARY KEY AUTOINCREMENT, "
               "date TEXT NOT NULL, "
               "employee_id INTEGER NOT NULL, "
               "toy_id INTEGER NOT NULL, "
               "process_id INTEGER NOT NULL, "
               "quantity INTEGER NOT NULL, "
               "piece_rate REAL NOT NULL, "
               "subtotal REAL NOT NULL, "
               "notes TEXT, "
               "created_at TEXT DEFAULT CURRENT_TIMESTAMP, "
               "updated_at TEXT DEFAULT CURRENT_TIMESTAMP, "
               "FOREIGN KEY (employee_id) REFERENCES employees(id), "
               "FOREIGN KEY (toy_id) REFERENCES toys(id), "
               "FOREIGN KEY (process_id) REFERENCES processes(id), "
               "UNIQUE(date, employee_id, toy_id, process_id))";
    query.prepare(createProductionV2Table);
    if (!executeQuery(query, "创建新版本生产记录表失败", this)) {
        db.rollback();
        return false;
    }

    // 创建班组表
    // 字段说明：
    // id: 班组ID，主键，自增
    // name: 班组名称，唯一
    QString createDepartmentsTable = "CREATE TABLE IF NOT EXISTS departments ("
               "id INTEGER PRIMARY KEY AUTOINCREMENT, "
               "name TEXT UNIQUE NOT NULL)";
    query.prepare(createDepartmentsTable);
    if (!executeQuery(query, "创建班组表失败", this)) {
        db.rollback();
        return false;
    }

    // 创建工序表 - 新增
    // 字段说明：
    // id: 工序ID，主键，自增
    // process_id: 工序编号，唯一标识
    // name: 工序名称
    // description: 工序描述
    // piece_rate: 计件单价，默认0.0
    // department_id: 所属班组ID，外键
    // effective_date: 生效日期，默认当前日期
    // status: 工序状态，默认'启用'
    // created_at: 创建时间，默认当前时间戳
    // updated_at: 更新时间，默认当前时间戳
    QString createProcessesTable = "CREATE TABLE IF NOT EXISTS processes ("
               "id INTEGER PRIMARY KEY AUTOINCREMENT, "
               "process_id TEXT UNIQUE NOT NULL, "
               "name TEXT NOT NULL, "
               "description TEXT, "
               "piece_rate REAL NOT NULL DEFAULT 0.0, "
               "department_id INTEGER, "
               "effective_date TEXT DEFAULT CURRENT_DATE, "
               "status TEXT DEFAULT '启用', "
               "created_at TEXT DEFAULT CURRENT_TIMESTAMP, "
               "updated_at TEXT DEFAULT CURRENT_TIMESTAMP, "
               "FOREIGN KEY (department_id) REFERENCES departments(id))";
    query.prepare(createProcessesTable);
    if (!executeQuery(query, "创建工序表失败", this)) {
        db.rollback();
        return false;
    }

    // 创建玩具工序关联表 - 新增
    // 字段说明：
    // id: 关联ID，主键，自增
    // toy_id: 玩具ID，外键
    // process_id: 工序ID，外键
    // sequence_order: 工序顺序，默认1
    // is_required: 是否必需，默认1(true)
    // estimated_time: 预估时间(分钟)，默认0
    // created_at: 创建时间，默认当前时间戳
    QString createToyProcessesTable = "CREATE TABLE IF NOT EXISTS toy_processes ("
               "id INTEGER PRIMARY KEY AUTOINCREMENT, "
               "toy_id INTEGER NOT NULL, "
               "process_id INTEGER NOT NULL, "
               "sequence_order INTEGER DEFAULT 1, "
               "is_required BOOLEAN DEFAULT 1, "
               "estimated_time INTEGER DEFAULT 0, "
               "created_at TEXT DEFAULT CURRENT_TIMESTAMP, "
               "FOREIGN KEY (toy_id) REFERENCES toys(id) ON DELETE CASCADE, "
               "FOREIGN KEY (process_id) REFERENCES processes(id) ON DELETE CASCADE, "
               "UNIQUE(toy_id, process_id))";
    query.prepare(createToyProcessesTable);
    if (!executeQuery(query, "创建玩具工序关联表失败", this)) {
        db.rollback();
        return false;
    }

    // 创建工价管理表 - 新增
    // 字段说明：
    // id: 工价ID，主键，自增
    // toy_id: 玩具ID，外键
    // total_wage: 总工价
    // employee_wage: 员工工价
    // profit: 利润
    // created_at: 创建时间，默认当前时间戳
    // updated_at: 更新时间，默认当前时间戳
    QString createWageManagementTable = "CREATE TABLE IF NOT EXISTS wage_management ("
               "id INTEGER PRIMARY KEY AUTOINCREMENT, "
               "toy_id INTEGER NOT NULL, "
               "total_wage REAL NOT NULL, "
               "employee_wage REAL NOT NULL, "
               "profit REAL NOT NULL, "
               "created_at TEXT DEFAULT CURRENT_TIMESTAMP, "
               "updated_at TEXT DEFAULT CURRENT_TIMESTAMP, "
               "FOREIGN KEY (toy_id) REFERENCES toys(id) ON DELETE CASCADE)";
    query.prepare(createWageManagementTable);
    if (!executeQuery(query, "创建工价管理表失败", this)) {
        db.rollback();
        return false;
    }

    // 检查是否需要数据迁移
    if (!migrateToProcessSystem()) {
        db.rollback();
        return false;
    }

    // 提交事务
    if (!db.commit()) {
        db.rollback();
        QMessageBox::critical(this, "事务错误", "创建数据表时提交事务失败：" + db.lastError().text());
        return false;
    }

    return true;
}

// 数据迁移函数 - 新增
// 功能：将旧版本的玩具数据迁移到新的工序系统中
// 迁移过程：
// 1. 检查是否已经迁移（查看processes表是否有数据）
// 2. 为每个玩具创建对应的默认工序
// 3. 建立玩具与工序的关联关系
bool MainWindow::migrateToProcessSystem()
{
    QSqlQuery query;

    // 检查是否已经迁移（查看processes表是否有数据）
    query.prepare("SELECT COUNT(*) FROM processes");
    if (executeQuery(query, "检查工序表数据失败", this) && query.next()) {
        if (query.value(0).toInt() > 0) {
            return true; // 已经迁移，跳过
        }
    }

    // 检查toys表是否有数据需要迁移
    query.prepare("SELECT COUNT(*) FROM toys");
    if (!executeQuery(query, "检查玩具表数据失败", this)) {
        return false;
    }

    if (!query.next() || query.value(0).toInt() == 0) {
        return true; // 没有数据需要迁移
    }

    // 开始数据迁移
    qDebug() << "开始数据迁移到工序系统...";

    // 1. 创建默认班组（如果不存在）
    query.prepare("INSERT OR IGNORE INTO departments (name) VALUES ('默认班组')");
    if (!executeQuery(query, "创建默认班组失败", this)) {
        return false;
    }

    // 获取默认班组ID
    query.prepare("SELECT id FROM departments WHERE name = '默认班组'");
    if (!executeQuery(query, "获取默认班组ID失败", this) || !query.next()) {
        return false;
    }
    int defaultDeptId = query.value(0).toInt();

    // 2. 为每个玩具创建对应的默认工序
    query.prepare("SELECT id, toy_id, name, piece_rate FROM toys ORDER BY id");
    if (!executeQuery(query, "查询玩具数据失败", this)) {
        return false;
    }

    int processIndex = 1;
    while (query.next()) {
        int toyId = query.value(0).toInt();
        QString toyCode = query.value(1).toString();
        QString toyName = query.value(2).toString();
        double pieceRate = query.value(3).toDouble();

        // 创建工序记录
        QString processId = QString("P%1").arg(processIndex, 3, 10, QChar('0'));
        QString processName = QString("生产-%1").arg(toyName);
        QString processDesc = QString("玩具 %1 的生产工序").arg(toyName);

        QSqlQuery insertProcessQuery;
        insertProcessQuery.prepare("INSERT INTO processes (process_id, name, description, piece_rate, department_id) "
                                  "VALUES (?, ?, ?, ?, ?)");
        insertProcessQuery.addBindValue(processId);
        insertProcessQuery.addBindValue(processName);
        insertProcessQuery.addBindValue(processDesc);
        insertProcessQuery.addBindValue(pieceRate);
        insertProcessQuery.addBindValue(defaultDeptId);

        if (!executeQuery(insertProcessQuery, QString("创建工序 %1 失败").arg(processName), this)) {
            return false;
        }

        // 获取新创建的工序 ID
        QSqlQuery getProcessIdQuery;
        getProcessIdQuery.prepare("SELECT id FROM processes WHERE process_id = ?");
        getProcessIdQuery.addBindValue(processId);
        if (!executeQuery(getProcessIdQuery, "获取工序 ID 失败", this) || !getProcessIdQuery.next()) {
            return false;
        }
        int newProcessId = getProcessIdQuery.value(0).toInt();

        // 创建玩具工序关联
        QSqlQuery linkQuery;
        linkQuery.prepare("INSERT INTO toy_processes (toy_id, process_id, sequence_order, is_required) "
                         "VALUES (?, ?, 1, 1)");
        linkQuery.addBindValue(toyId);
        linkQuery.addBindValue(newProcessId);

        if (!executeQuery(linkQuery, QString("创建玩具工序关联 %1 失败").arg(toyName), this)) {
            return false;
        }

        processIndex++;
    }

    qDebug() << QString("数据迁移完成，共创建 %1 个工序").arg(processIndex - 1);
    return true;
}

// 初始化工序管理界面 - 新增
void MainWindow::setupProcessManagementUI()
{
    // 在基础数据管理Tab中添加工序管理子Tab
    QWidget *processTab = new QWidget();
    ui->basicDataSubTab->addTab(processTab, "工序管理");

    // 创建工序管理界面布局
    QVBoxLayout *processLayout = new QVBoxLayout(processTab);

    // 添加搜索和操作按钮区域
    QHBoxLayout *processTopLayout = new QHBoxLayout();

    // 搜索区域
    QLabel *searchLabel = new QLabel("工序搜索：");
    QLineEdit *searchProcessEdit = new QLineEdit();
    searchProcessEdit->setObjectName("lineEdit_searchProcess");
    searchProcessEdit->setPlaceholderText("请输入工序名称或编号");
    QPushButton *searchProcessBtn = new QPushButton("搜索");
    searchProcessBtn->setObjectName("pushButton_searchProcess");
    QPushButton *resetProcessBtn = new QPushButton("重置");
    resetProcessBtn->setObjectName("pushButton_resetProcess");

    processTopLayout->addWidget(searchLabel);
    processTopLayout->addWidget(searchProcessEdit);
    processTopLayout->addWidget(searchProcessBtn);
    processTopLayout->addWidget(resetProcessBtn);
    processTopLayout->addStretch();

    // 操作按钮
    QPushButton *addProcessBtn = new QPushButton("添加工序");
    addProcessBtn->setObjectName("pushButton_addProcess");
    QPushButton *editProcessBtn = new QPushButton("编辑工序");
    editProcessBtn->setObjectName("pushButton_editProcess");
    QPushButton *deleteProcessBtn = new QPushButton("删除工序");
    deleteProcessBtn->setObjectName("pushButton_deleteProcess");

    processTopLayout->addWidget(addProcessBtn);
    processTopLayout->addWidget(editProcessBtn);
    processTopLayout->addWidget(deleteProcessBtn);

    processLayout->addLayout(processTopLayout);

    // 添加工序表格
    QTableWidget *processTable = new QTableWidget();
    processTable->setObjectName("tableWidget_processes");
    processTable->setColumnCount(6);
    processTable->setHorizontalHeaderLabels(QStringList()
        << "工序编号" << "工序名称" << "描述" << "计件单价(元)" << "所属班组" << "操作");
    processTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    processTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    processTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    processTable->setAlternatingRowColors(true);

    // 应用表格样式
    QString tableStyle = ui->tableWidget_employees->styleSheet();
    processTable->setStyleSheet(tableStyle);

    processLayout->addWidget(processTable);
    
    // 添加分页控件
    QHBoxLayout *processPaginationLayout = new QHBoxLayout();
    processPaginationLayout->setSpacing(6);
    processPaginationLayout->setContentsMargins(0, 0, 0, 0);
    
    // 添加弹性空间，将分页控件推到右侧
    QSpacerItem *horizontalSpacer_process = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
    processPaginationLayout->addItem(horizontalSpacer_process);
    
    // 首页按钮
    pushButton_firstPageProcess = new QPushButton("«");
    pushButton_firstPageProcess->setObjectName("pushButton_firstPageProcess");
    pushButton_firstPageProcess->setMaximumSize(QSize(30, 16777215));
    processPaginationLayout->addWidget(pushButton_firstPageProcess);
    
    // 上一页按钮
    pushButton_prevPageProcess = new QPushButton("‹");
    pushButton_prevPageProcess->setObjectName("pushButton_prevPageProcess");
    pushButton_prevPageProcess->setMaximumSize(QSize(30, 16777215));
    processPaginationLayout->addWidget(pushButton_prevPageProcess);
    
    // 页面信息标签
    label_pageInfoProcess = new QLabel("1/1");
    label_pageInfoProcess->setObjectName("label_pageInfoProcess");
    label_pageInfoProcess->setAlignment(Qt::AlignCenter);
    processPaginationLayout->addWidget(label_pageInfoProcess);
    
    // 下一页按钮
    pushButton_nextPageProcess = new QPushButton("›");
    pushButton_nextPageProcess->setObjectName("pushButton_nextPageProcess");
    pushButton_nextPageProcess->setMaximumSize(QSize(30, 16777215));
    processPaginationLayout->addWidget(pushButton_nextPageProcess);
    
    // 末页按钮
    pushButton_lastPageProcess = new QPushButton("»");
    pushButton_lastPageProcess->setObjectName("pushButton_lastPageProcess");
    pushButton_lastPageProcess->setMaximumSize(QSize(30, 16777215));
    processPaginationLayout->addWidget(pushButton_lastPageProcess);
    
    processLayout->addLayout(processPaginationLayout);

    // 连接信号槽
    connect(searchProcessBtn, &QPushButton::clicked, this, &MainWindow::onSearchProcess);
    connect(resetProcessBtn, &QPushButton::clicked, this, &MainWindow::onResetProcess);
    connect(searchProcessEdit, &QLineEdit::returnPressed, this, &MainWindow::onSearchProcess);

    connect(addProcessBtn, &QPushButton::clicked, this, &MainWindow::onAddProcess);
    connect(editProcessBtn, &QPushButton::clicked, this, &MainWindow::onEditProcess);
    connect(deleteProcessBtn, &QPushButton::clicked, this, &MainWindow::onDeleteProcess);
    
    // 连接分页按钮信号槽
    connect(pushButton_firstPageProcess, &QPushButton::clicked, [this]() {
        onProcessPageChanged(0);
    });
    connect(pushButton_prevPageProcess, &QPushButton::clicked, [this]() {
        if (currentProcessPage > 0) {
            onProcessPageChanged(currentProcessPage - 1);
        }
    });
    connect(pushButton_nextPageProcess, &QPushButton::clicked, [this]() {
        int totalPages = (totalProcessRecords + itemsPerPage - 1) / itemsPerPage;
        if (currentProcessPage < totalPages - 1) {
            onProcessPageChanged(currentProcessPage + 1);
        }
    });
    connect(pushButton_lastPageProcess, &QPushButton::clicked, [this]() {
        int totalPages = (totalProcessRecords + itemsPerPage - 1) / itemsPerPage;
        onProcessPageChanged(totalPages - 1);
    });
}

// 加载工序数据 - 新增
void MainWindow::loadProcesses()
{
    QTableWidget *processTable = findChild<QTableWidget*>("tableWidget_processes");
    if (!processTable) return;

    processTable->setRowCount(0);

    QSqlQuery query("SELECT p.process_id, p.name, p.description, p.piece_rate, d.name as dept_name "
                   "FROM processes p "
                   "LEFT JOIN departments d ON p.department_id = d.id "
                   "ORDER BY p.process_id");

    int row = 0;
    while (query.next()) {
        processTable->insertRow(row);
        processTable->setItem(row, 0, new QTableWidgetItem(query.value(0).toString())); // 工序编号
        processTable->setItem(row, 1, new QTableWidgetItem(query.value(1).toString())); // 工序名称
        processTable->setItem(row, 2, new QTableWidgetItem(query.value(2).toString())); // 描述
        processTable->setItem(row, 3, new QTableWidgetItem(QString::number(query.value(3).toDouble(), 'f', 3))); // 计件单价
        processTable->setItem(row, 4, new QTableWidgetItem(query.value(4).toString())); // 班组

        // 添加操作按钮
        QPushButton *editBtn = new QPushButton("编辑");
        editBtn->setStyleSheet("QPushButton { background-color: #3498db; color: white; border: none; padding: 4px 8px; border-radius: 2px; }");
        connect(editBtn, &QPushButton::clicked, [this, row]() {
            QTableWidget *table = findChild<QTableWidget*>("tableWidget_processes");
            if (table) {
                table->selectRow(row);
                onEditProcess();
            }
        });
        processTable->setCellWidget(row, 5, editBtn);

        row++;
    }
}

// 添加工序 - 新增
void MainWindow::onAddProcess()
{
    ProcessDialog dialog(this);
    if (dialog.exec() == QDialog::Accepted) {
        // 获取输入的工序信息
        QString processId = dialog.getProcessId();
        QString name = dialog.getProcessName();
        QString description = dialog.getDescription();
        double pieceRate = dialog.getPieceRate();
        int departmentId = dialog.getDepartmentId();

        // 插入到数据库
        QSqlQuery query;
        query.prepare("INSERT INTO processes (process_id, name, description, piece_rate, department_id) "
                     "VALUES (?, ?, ?, ?, ?)");
        query.addBindValue(processId);
        query.addBindValue(name);
        query.addBindValue(description);
        query.addBindValue(pieceRate);
        query.addBindValue(departmentId);

        if (executeQuery(query, "添加工序失败", this)) {
            QMessageBox::information(this, "成功", "工序添加成功");
            loadProcessesWithPagination(currentProcessPage);  // 使用分页加载
            updateDashboard();
        }
    }
}

// 编辑工序 - 新增
void MainWindow::onEditProcess()
{
    QTableWidget *processTable = findChild<QTableWidget*>("tableWidget_processes");
    if (!processTable) return;

    int currentRow = processTable->currentRow();
    if (currentRow < 0) {
        QMessageBox::warning(this, "警告", "请先选择要编辑的工序");
        return;
    }

    // 获取当前选中的工序信息
    QString processId = processTable->item(currentRow, 0)->text();

    // 从数据库查询完整的工序信息
    QSqlQuery query;
    query.prepare("SELECT process_id, name, description, piece_rate, department_id "
                 "FROM processes WHERE process_id = ?");
    query.addBindValue(processId);

    if (!executeQuery(query, "查询工序信息失败", this) || !query.next()) {
        QMessageBox::warning(this, "错误", "无法获取工序信息");
        return;
    }

    // 创建编辑对话框
    ProcessDialog dialog(processId, this);

    // 设置当前工序信息
    dialog.setProcessInfo(
        query.value(0).toString(),  // process_id
        query.value(1).toString(),  // name
        query.value(2).toString(),  // description
        query.value(3).toDouble(),  // piece_rate
        query.value(4).toInt()     // department_id
    );

    if (dialog.exec() == QDialog::Accepted) {
        // 获取更新后的信息
        QString newName = dialog.getProcessName();
        QString newDescription = dialog.getDescription();
        double newPieceRate = dialog.getPieceRate();
        int newDepartmentId = dialog.getDepartmentId();

        // 更新数据库
        QSqlQuery updateQuery;
        updateQuery.prepare("UPDATE processes SET name = ?, description = ?, piece_rate = ?, "
                           "department_id = ?, updated_at = CURRENT_TIMESTAMP "
                           "WHERE process_id = ?");
        updateQuery.addBindValue(newName);
        updateQuery.addBindValue(newDescription);
        updateQuery.addBindValue(newPieceRate);
        updateQuery.addBindValue(newDepartmentId);
        updateQuery.addBindValue(processId);

        if (executeQuery(updateQuery, "更新工序失败", this)) {
            QMessageBox::information(this, "成功", "工序更新成功");
            loadProcessesWithPagination(currentProcessPage);  // 使用分页加载
            updateDashboard();
        }
    }
}

// 删除工序 - 新增
void MainWindow::onDeleteProcess()
{
    QTableWidget *processTable = findChild<QTableWidget*>("tableWidget_processes");
    if (!processTable) return;

    int currentRow = processTable->currentRow();
    if (currentRow < 0) {
        QMessageBox::warning(this, "警告", "请先选择要删除的工序");
        return;
    }

    QString processId = processTable->item(currentRow, 0)->text();
    QString processName = processTable->item(currentRow, 1)->text();

    if (QMessageBox::question(this, "确认删除", "确定要删除工序 " + processName + " 吗？") == QMessageBox::Yes) {
        QSqlQuery query;
        query.prepare("DELETE FROM processes WHERE process_id = ?");
        query.addBindValue(processId);

        if (executeQuery(query, "删除工序失败", this)) {
            QMessageBox::information(this, "成功", "工序删除成功");
            loadProcessesWithPagination(currentProcessPage);  // 使用分页加载
            updateDashboard();
        }
    }
}

// 搜索工序 - 新增
void MainWindow::onSearchProcess()
{
    QLineEdit *searchEdit = findChild<QLineEdit*>("lineEdit_searchProcess");
    QTableWidget *processTable = findChild<QTableWidget*>("tableWidget_processes");
    if (!searchEdit || !processTable) return;

    QString searchText = searchEdit->text().trimmed();

    if (searchText.isEmpty()) {
        loadProcessesWithPagination(currentProcessPage);  // 使用分页加载
        return;
    }

    processTable->setRowCount(0);

    // 计算偏移量
    int offset = currentProcessPage * itemsPerPage;

    // 查询总记录数
    QSqlQuery countQuery;
    countQuery.prepare("SELECT COUNT(*) "
                      "FROM processes p "
                      "LEFT JOIN departments d ON p.department_id = d.id "
                      "WHERE p.process_id LIKE ? OR p.name LIKE ? OR p.description LIKE ?");
    QString likePattern = "%" + searchText + "%";
    countQuery.addBindValue(likePattern);
    countQuery.addBindValue(likePattern);
    countQuery.addBindValue(likePattern);
    
    int totalRecords = 0;
    if (executeQuery(countQuery, "查询工序总数失败", this) && countQuery.next()) {
        totalRecords = countQuery.value(0).toInt();
    }
    totalProcessRecords = totalRecords; // 保存总记录数

    // 计算总页数
    int totalPages = (totalRecords + itemsPerPage - 1) / itemsPerPage;

    // 查询当前页数据
    QSqlQuery query;
    query.prepare("SELECT p.process_id, p.name, p.description, p.piece_rate, d.name as dept_name "
                 "FROM processes p "
                 "LEFT JOIN departments d ON p.department_id = d.id "
                 "WHERE p.process_id LIKE ? OR p.name LIKE ? OR p.description LIKE ? "
                 "ORDER BY p.process_id "
                 "LIMIT ? OFFSET ?");
    query.addBindValue(likePattern);
    query.addBindValue(likePattern);
    query.addBindValue(likePattern);
    query.addBindValue(itemsPerPage);
    query.addBindValue(offset);

    if (executeQuery(query, "搜索工序失败", this)) {
        int row = 0;
        while (query.next()) {
            processTable->insertRow(row);
            processTable->setItem(row, 0, new QTableWidgetItem(query.value(0).toString()));
            processTable->setItem(row, 1, new QTableWidgetItem(query.value(1).toString()));
            processTable->setItem(row, 2, new QTableWidgetItem(query.value(2).toString()));
            processTable->setItem(row, 3, new QTableWidgetItem(QString::number(query.value(3).toDouble(), 'f', 3)));
            processTable->setItem(row, 4, new QTableWidgetItem(query.value(4).toString()));

            // 添加操作按钮
            QPushButton *editBtn = new QPushButton("编辑");
            editBtn->setStyleSheet("QPushButton { background-color: #3498db; color: white; border: none; padding: 4px 8px; border-radius: 2px; }");
            connect(editBtn, &QPushButton::clicked, [this, row]() {
                QTableWidget *table = findChild<QTableWidget*>("tableWidget_processes");
                if (table) {
                    table->selectRow(row);
                    onEditProcess();
                }
            });
            processTable->setCellWidget(row, 5, editBtn);

            row++;
        }
        
        // 更新分页控件状态
        updatePaginationControls("process", currentProcessPage, totalPages);
    }

    statusBar()->showMessage(QString("搜索到 %1 个工序").arg(totalRecords));
}

// 重置工序搜索 - 新增
void MainWindow::onResetProcess()
{
    QLineEdit *searchEdit = findChild<QLineEdit*>("lineEdit_searchProcess");
    if (!searchEdit) return;

    searchEdit->clear();
    loadProcessesWithPagination(currentProcessPage);
}

// 分页功能实现 - 工序管理分页
void MainWindow::onProcessPageChanged(int page)
{
    currentProcessPage = page;
    loadProcessesWithPagination(page);
}

// 带分页的工序数据加载
void MainWindow::loadProcessesWithPagination(int page)
{
    QTableWidget *processTable = findChild<QTableWidget*>("tableWidget_processes");
    if (!processTable) return;

    processTable->setRowCount(0);

    // 计算偏移量
    int offset = page * itemsPerPage;

    // 查询总记录数
    QSqlQuery countQuery("SELECT COUNT(*) FROM processes");
    int totalRecords = 0;
    if (executeQuery(countQuery, "查询工序总数失败", this) && countQuery.next()) {
        totalRecords = countQuery.value(0).toInt();
    }
    totalProcessRecords = totalRecords; // 保存总记录数

    // 计算总页数
    int totalPages = (totalRecords + itemsPerPage - 1) / itemsPerPage;

    // 查询当前页数据
    QSqlQuery query;
    query.prepare("SELECT p.process_id, p.name, p.description, p.piece_rate, d.name as dept_name "
                  "FROM processes p "
                  "LEFT JOIN departments d ON p.department_id = d.id "
                  "ORDER BY p.process_id "
                  "LIMIT ? OFFSET ?");
    query.addBindValue(itemsPerPage);
    query.addBindValue(offset);

    if (executeQuery(query, "查询工序分页数据失败", this)) {
        int row = 0;
        while (query.next()) {
            processTable->insertRow(row);
            processTable->setItem(row, 0, new QTableWidgetItem(query.value(0).toString())); // 工序编号
            processTable->setItem(row, 1, new QTableWidgetItem(query.value(1).toString())); // 工序名称
            processTable->setItem(row, 2, new QTableWidgetItem(query.value(2).toString())); // 描述
            processTable->setItem(row, 3, new QTableWidgetItem(QString::number(query.value(3).toDouble(), 'f', 3))); // 计件单价
            processTable->setItem(row, 4, new QTableWidgetItem(query.value(4).toString())); // 班组

            // 添加操作按钮
            QPushButton *editBtn = new QPushButton("编辑");
            editBtn->setStyleSheet("QPushButton { background-color: #3498db; color: white; border: none; padding: 4px 8px; border-radius: 2px; }");
            connect(editBtn, &QPushButton::clicked, [this, row]() {
                QTableWidget *table = findChild<QTableWidget*>("tableWidget_processes");
                if (table) {
                    table->selectRow(row);
                    onEditProcess();
                }
            });
            processTable->setCellWidget(row, 5, editBtn);

            row++;
        }
    }

    // 更新分页控件状态
    updatePaginationControls("process", page, totalPages);
}



// 加载模拟数据
bool MainWindow::loadMockData()
{
    QSqlQuery query;

    // 检查是否已有数据
    query.prepare("SELECT COUNT(*) FROM employees");
    if (!executeQuery(query, "检查员工表数据时失败", this)) {
        return false;
    }

    if (query.next() && query.value(0).toInt() > 0) {
        return true; // 已有数据，不加载模拟数据
    }

    // 开始事务
    if (!beginTransaction(db, "加载模拟数据时开启事务失败", this)) {
        return false;
    }

    // 生产环境不插入模拟员工数据，由管理员根据实际情况添加
    // 如需测试数据，可以取消以下注释：
    /*
    QString insertEmployees = "INSERT INTO employees (employee_id, name, team, hire_date, contact, status) VALUES "
               "('001', '张三', '毛绒组', '2023-01-01', '', '在职'), "
               "('002', '李四', '塑料组', '2023-02-15', '', '在职'), "
               "('003', '王五', '毛绒组', '2023-03-10', '', '在职'), "
               "('004', '赵六', '塑料组', '2023-04-20', '', '在职')";
    query.prepare(insertEmployees);
    if (!executeQuery(query, "插入模拟员工数据失败", this)) {
        db.rollback();
        return false;
    }
    */

    // 生产环境不插入模拟玩具数据，由管理员根据实际产品添加
    // 如需测试数据，可以取消以下注释：
    /*
    QString insertToys = "INSERT INTO toys (toy_id, name, description, piece_rate) VALUES "
               "('T001', '毛绒熊', '可爱的毛绒玩具', 5.0), "
               "('T002', '塑料小车', '儿童塑料玩具车', 2.0), "
               "('T003', '积木套装', '益智积木玩具', 8.0), "
               "('T004', '遥控飞机', '遥控飞行玩具', 15.0)";
    query.prepare(insertToys);
    if (!executeQuery(query, "插入模拟玩具数据失败", this)) {
        db.rollback();
        return false;
    }
    */

    // 生产环境不插入模拟生产记录，让用户根据实际情况录入
    // 如需测试数据，可以取消以下注释：
    /*
    QString insertProduction = "INSERT INTO production (date, employee_id, toy_id, quantity) VALUES "
               "('2024-01-15', 1, 1, 20), "
               "('2024-01-15', 1, 2, 50), "
               "('2024-01-16', 1, 1, 25), "
               "('2024-01-15', 2, 2, 100), "
               "('2024-01-16', 2, 2, 80), "
               "('2024-01-15', 3, 1, 30), "
               "('2024-01-16', 3, 1, 35), "
               "('2024-01-15', 4, 3, 15), "
               "('2024-01-16', 4, 3, 20)";
    query.prepare(insertProduction);
    if (!executeQuery(query, "插入模拟生产数据失败", this)) {
        db.rollback();
        return false;
    }
    */

    // 提交事务
    if (!db.commit()) {
        db.rollback();
        QMessageBox::critical(this, "事务错误", "加载模拟数据时提交事务失败：" + db.lastError().text());
        return false;
    }

    return true;
}

// 初始化UI组件
void MainWindow::initUI()
{
    // 设置表格列数和表头
    // 员工管理表格
    ui->tableWidget_employees->setColumnCount(7);
    ui->tableWidget_employees->setHorizontalHeaderLabels(QStringList() << "员工编号" << "姓名" << "所属班组" << "入职日期" << "联系方式" << "状态" << "操作");
    ui->tableWidget_employees->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    // 设置表格行高
    ui->tableWidget_employees->verticalHeader()->setDefaultSectionSize(50);

    // 玩具管理表格 - 移除计件单价列
    ui->tableWidget_products->setColumnCount(4);
    ui->tableWidget_products->setHorizontalHeaderLabels(QStringList() << "玩具编号" << "玩具名称" << "描述" << "操作");
    ui->tableWidget_products->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    // 设置表格行高
    ui->tableWidget_products->verticalHeader()->setDefaultSectionSize(50);

    // 生产录入表格 - 新版本支持工序维度
    ui->tableWidget_productionEntry->setColumnCount(6);
    ui->tableWidget_productionEntry->setHorizontalHeaderLabels(QStringList() << "玩具产品" << "工序名称" << "计件单价" << "生产数量" << "小计金额" << "操作");
    ui->tableWidget_productionEntry->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    // 设置表格行高和显示属性
    ui->tableWidget_productionEntry->setRowHeight(0, 50); // 设置默认行高
    ui->tableWidget_productionEntry->verticalHeader()->setDefaultSectionSize(50);
    ui->tableWidget_productionEntry->setAlternatingRowColors(true);
    ui->tableWidget_productionEntry->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidget_productionEntry->setShowGrid(true);

    // 确保表格可见且正确显示
    ui->tableWidget_productionEntry->setVisible(true);
    ui->tableWidget_productionEntry->show();

    // 日报表表格 - 支持工序维度
    ui->tableWidget_dailyReport->setColumnCount(7);
    ui->tableWidget_dailyReport->setHorizontalHeaderLabels(QStringList() << "日期" << "玩具名称" << "工序名称" << "数量" << "单价" << "小计金额" << "当日总收入");
    ui->tableWidget_dailyReport->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    // 设置表格行高
    ui->tableWidget_dailyReport->verticalHeader()->setDefaultSectionSize(50);

    // 月报表表格 - 支持工序维度
    ui->tableWidget_monthlyReport->setColumnCount(5);
    ui->tableWidget_monthlyReport->setHorizontalHeaderLabels(QStringList() << "玩具名称" << "工序名称" << "总数量" << "单价" << "计件收入");
    ui->tableWidget_monthlyReport->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    // 设置表格行高
    ui->tableWidget_monthlyReport->verticalHeader()->setDefaultSectionSize(50);

    // 生产统计表格
    ui->tableWidget_factoryStats->setColumnCount(6);
    ui->tableWidget_factoryStats->setHorizontalHeaderLabels(QStringList() << "日期/月份" << "玩具名称" << "总产量" << "总产值" << "参与人数" << "操作");
    ui->tableWidget_factoryStats->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    // 设置表格行高
    ui->tableWidget_factoryStats->verticalHeader()->setDefaultSectionSize(50);

    // 工资条表格
    ui->tableWidget_wageDetails->setColumnCount(6);
    ui->tableWidget_wageDetails->setHorizontalHeaderLabels(QStringList() << "员工名称" << "玩具名称" << "工序名称" << "数量" << "单价" << "金额");
    ui->tableWidget_wageDetails->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    // 设置表格行高
    ui->tableWidget_wageDetails->verticalHeader()->setDefaultSectionSize(50);

    // 班组管理表格
    ui->tableWidget_departments->setColumnCount(2);
    ui->tableWidget_departments->setHorizontalHeaderLabels(QStringList() << "班组名称" << "操作");
    ui->tableWidget_departments->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    // 设置表格行高
    ui->tableWidget_departments->verticalHeader()->setDefaultSectionSize(50);

    // 最近活动表格
    ui->recentActivityTable->setColumnCount(6);
    ui->recentActivityTable->setHorizontalHeaderLabels(QStringList() << "日期" << "员工" << "玩具" << "工序" << "数量" << "金额");
    ui->recentActivityTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    // 设置表格行高
    ui->recentActivityTable->verticalHeader()->setDefaultSectionSize(50);

    // 初始化状态栏
    statusBar()->showMessage("系统就绪");
    
    // 初始化统计周期选择控件
    // 默认选择"按日"，隐藏结束日期控件
    ui->comboBox_statsPeriod->setCurrentIndex(0);
    ui->label_statsEndDate->setVisible(false);
    ui->dateEdit_statsEndDate->setVisible(false);
    // 设置结束日期控件的默认值为当前日期
    ui->dateEdit_statsEndDate->setDate(QDate::currentDate());
}

// 初始化样式
void MainWindow::initStyles()
{
    // 设置全局字体大小
    QFont globalFont = QApplication::font();
    globalFont.setPointSize(25); // 全局字体设置为16号
    QApplication::setFont(globalFont);

    // 设置主窗口样式
    this->setStyleSheet(""
        "QMainWindow {"
        "    background-color: #f5f5f5;"
        "    font-size: 25px;"
        "}"
        "QTabWidget::pane {"
        "    border: 1px solid #cccccc;"
        "    background-color: white;"
        "    font-size: 25px;"
        "}"
        "QTabBar::tab {"
        "    background-color: #e9ecef;"
        "    border: 1px solid #cccccc;"
        "    padding: 12px 24px;"
        "    margin-right: 2px;"
        "    border-top-left-radius: 4px;"
        "    border-top-right-radius: 4px;"
        "    font-size: 25px;"
        "}"
        "QTabBar::tab:selected {"
        "    background-color: white;"
        "    border-bottom: 1px solid white;"
        "    font-weight: bold;"
        "}"
        "QTabBar::tab:hover {"
        "    background-color: #dee2e6;"
        "}"
    );

    // 设置表格样式
    QString tableStyle = ""
        "QTableWidget {"
        "    gridline-color: #e0e0e0;"
        "    background-color: white;"
        "    alternate-background-color: #f8f9fa;"
        "    selection-background-color: #007bff;"
        "    selection-color: white;"
        "    border: 1px solid #dee2e6;"
        "    border-radius: 4px;"
        "    font-size: 25px;"  // 增大表格字体到16px
        "}"
        "QTableWidget::item {"
        "    padding: 12px;"
        "    border-bottom: 1px solid #e9ecef;"
        "}"
        "QTableWidget::item:selected {"
        "    background-color: #007bff;"
        "    color: white;"
        "}"
        "QHeaderView::section {"
        "    background-color: #6c757d;"
        "    color: white;"
        "    padding: 12px;"
        "    border: none;"
        "    font-weight: bold;"
        "    font-size: 25px;"
        "}"
        "QHeaderView::section:hover {"
        "    background-color: #5a6268;"
        "}";

    // 为所有表格应用样式，特别增大生产录入表格的字体
    ui->tableWidget_employees->setStyleSheet(tableStyle);
    ui->tableWidget_products->setStyleSheet(tableStyle);
    ui->tableWidget_departments->setStyleSheet(tableStyle);
    
    // 特别为生产录入表格设置更大的字体
    QString productionTableStyle = tableStyle;
    productionTableStyle.replace("font-size: 25px;", "font-size: 25px;");  // 生产录入表格使用18px字体
    ui->tableWidget_productionEntry->setStyleSheet(productionTableStyle);
    
    ui->tableWidget_dailyReport->setStyleSheet(tableStyle);
    ui->tableWidget_monthlyReport->setStyleSheet(tableStyle);
    ui->tableWidget_factoryStats->setStyleSheet(tableStyle);
    ui->tableWidget_wageDetails->setStyleSheet(tableStyle);
    ui->recentActivityTable->setStyleSheet(tableStyle);

    // 启用交替行颜色
    ui->tableWidget_employees->setAlternatingRowColors(true);
    ui->tableWidget_products->setAlternatingRowColors(true);
    ui->tableWidget_departments->setAlternatingRowColors(true);
    ui->tableWidget_productionEntry->setAlternatingRowColors(true);
    ui->tableWidget_dailyReport->setAlternatingRowColors(true);
    ui->tableWidget_monthlyReport->setAlternatingRowColors(true);
    ui->tableWidget_factoryStats->setAlternatingRowColors(true);
    ui->tableWidget_wageDetails->setAlternatingRowColors(true);
    ui->recentActivityTable->setAlternatingRowColors(true);

    // 设置按钮样式
    QString primaryButtonStyle = ""
        "QPushButton {"
        "    background-color: #007bff;"
        "    color: white;"
        "    border: none;"
        "    padding: 12px 24px;"
        "    border-radius: 4px;"
        "    font-weight: bold;"
        "    min-width: 120px;"
        "    font-size: 25px;"
        "}"
        "QPushButton:hover {"
        "    background-color: #0056b3;"
        "}"
        "QPushButton:pressed {"
        "    background-color: #004085;"
        "}"
        "QPushButton:disabled {"
        "    background-color: #6c757d;"
        "}";

    QString successButtonStyle = ""
        "QPushButton {"
        "    background-color: #28a745;"
        "    color: white;"
        "    border: none;"
        "    padding: 12px 24px;"
        "    border-radius: 4px;"
        "    font-weight: bold;"
        "    min-width: 120px;"
        "    font-size: 25px;"
        "}"
        "QPushButton:hover {"
        "    background-color: #1e7e34;"
        "}"
        "QPushButton:pressed {"
        "    background-color: #155724;"
        "}";

    QString dangerButtonStyle = ""
        "QPushButton {"
        "    background-color: #dc3545;"
        "    color: white;"
        "    border: none;"
        "    padding: 12px 24px;"
        "    border-radius: 4px;"
        "    font-weight: bold;"
        "    min-width: 120px;"
        "    font-size: 25px;"
        "}"
        "QPushButton:hover {"
        "    background-color: #c82333;"
        "}"
        "QPushButton:pressed {"
        "    background-color: #a71e2a;"
        "}";

    // 应用按钮样式
    ui->pushButton_addEmployee->setStyleSheet(successButtonStyle);
    ui->pushButton_updateEmployee->setStyleSheet(primaryButtonStyle);
    ui->pushButton_deleteEmployee->setStyleSheet(dangerButtonStyle);
    ui->pushButton_searchEmployee->setStyleSheet(primaryButtonStyle);

    ui->pushButton_addProduct->setStyleSheet(successButtonStyle);
    ui->pushButton_updateProduct->setStyleSheet(primaryButtonStyle);
    ui->pushButton_deleteProduct->setStyleSheet(dangerButtonStyle);
    ui->pushButton_searchProduct->setStyleSheet(primaryButtonStyle);

    ui->pushButton_addDepartment->setStyleSheet(successButtonStyle);
    ui->pushButton_deleteDepartment->setStyleSheet(dangerButtonStyle);

    ui->pushButton_addEntryRow->setStyleSheet(successButtonStyle);
    ui->pushButton_removeEntryRow->setStyleSheet(dangerButtonStyle);
    ui->pushButton_saveProductionData->setStyleSheet(primaryButtonStyle);
    ui->pushButton_loadEmployee->setStyleSheet(primaryButtonStyle);

    ui->pushButton_queryDailyReport->setStyleSheet(primaryButtonStyle);
    ui->pushButton_queryMonthlyReport->setStyleSheet(primaryButtonStyle);
    ui->pushButton_queryFactoryStats->setStyleSheet(primaryButtonStyle);

    ui->pushButton_calculateWage->setStyleSheet(primaryButtonStyle);

    ui->pushButton_exportDailyReport->setStyleSheet(primaryButtonStyle);
    ui->pushButton_exportMonthlyReport->setStyleSheet(primaryButtonStyle);
    ui->pushButton_exportFactoryStats->setStyleSheet(primaryButtonStyle);
    ui->pushButton_exportWageDetails->setStyleSheet(primaryButtonStyle);

    // 设置输入框样式
    QString inputStyle = ""
        "QLineEdit, QDateEdit, QDoubleSpinBox, QComboBox {"
        "    border: 1px solid #ced4da;"
        "    border-radius: 4px;"
        "    padding: 10px 18px;"
        "    background-color: white;"
        "    font-size: 25px;"
        "    min-height: 35px;"
        "}"
        "QLineEdit:focus, QDateEdit:focus, QDoubleSpinBox:focus, QComboBox:focus {"
        "    border-color: #007bff;"
        "    outline: none;"
        "}";

    ui->lineEdit_searchEmployee->setStyleSheet(inputStyle);

    ui->lineEdit_searchProduct->setStyleSheet(inputStyle);

    ui->lineEdit_departmentName->setStyleSheet(inputStyle);

    ui->dateEdit_entryDate->setStyleSheet(inputStyle);
    ui->comboBox_entryEmployee->setStyleSheet(inputStyle);

    ui->comboBox_dailyReportEmployee->setStyleSheet(inputStyle);
    ui->dateEdit_startDate->setStyleSheet(inputStyle);
    ui->dateEdit_endDate->setStyleSheet(inputStyle);

    ui->comboBox_monthlyReportEmployee->setStyleSheet(inputStyle);
    ui->dateEdit_month->setStyleSheet(inputStyle);

    ui->comboBox_statsType->setStyleSheet(inputStyle);
    ui->comboBox_statsDepartment->setStyleSheet(inputStyle);
    ui->comboBox_statsPeriod->setStyleSheet(inputStyle);

    ui->comboBox_wageEmployee->setStyleSheet(inputStyle);
    ui->dateEdit_wageMonth->setStyleSheet(inputStyle);

    // 设置统计显示样式
    QString statsLabelStyle = ""
        "QLabel {"
        "    background-color: white;"
        "    border: 1px solid #dee2e6;"
        "    border-radius: 8px;"
        "    padding: 25px;"
        "    margin: 6px;"
        "    font-size: 25px;"
        "}"
        "QLabel[objectName*=\"value_\"] {"
        "    color: #007bff;"
        "    font-weight: bold;"
        "}";

    ui->todayProductionLabel->setStyleSheet(statsLabelStyle);
    ui->todayRevenueLabel->setStyleSheet(statsLabelStyle);
    ui->totalEmployeeLabel->setStyleSheet(statsLabelStyle);
    ui->presentEmployeeLabel->setStyleSheet(statsLabelStyle);
    ui->productCountLabel->setStyleSheet(statsLabelStyle);
    ui->topProductLabel->setStyleSheet(statsLabelStyle);

    ui->value_wageEmployeeName->setStyleSheet(statsLabelStyle);
    ui->value_wagePeriod->setStyleSheet(statsLabelStyle);
    ui->value_totalProduction->setStyleSheet(statsLabelStyle);
    ui->value_wageAmount->setStyleSheet(statsLabelStyle);

    // 设置状态栏样式
    statusBar()->setStyleSheet(""
        "QStatusBar {"
        "    background-color: #f8f9fa;"
        "    border-top: 1px solid #dee2e6;"
        "    color: #495057;"
        "    font-weight: bold;"
        "    font-size: 25px;"
        "}"
    );

    // 设置 GroupBox 样式
    QString groupBoxStyle = ""
        "QGroupBox {"
        "    font-weight: bold;"
        "    border: 2px solid #dee2e6;"
        "    border-radius: 8px;"
        "    margin-top: 12px;"
        "    padding-top: 12px;"
        "    background-color: white;"
        "    font-size: 25px;"
        "}"
        "QGroupBox::title {"
        "    subcontrol-origin: margin;"
        "    left: 24px;"
        "    padding: 0 12px 0 12px;"
        "    color: #495057;"
        "    font-size: 25px;"
        "}";

    ui->productionOverviewGroup->setStyleSheet(groupBoxStyle);
    ui->employeeOverviewGroup->setStyleSheet(groupBoxStyle);
    ui->productOverviewGroup->setStyleSheet(groupBoxStyle);
    ui->recentActivityGroup->setStyleSheet(groupBoxStyle);
    ui->wageSummaryGroup->setStyleSheet(groupBoxStyle);
    
    // 特别增大生产录入相关控件的字体
    QString largeInputStyle = inputStyle;
    largeInputStyle.replace("font-size: 25px;", "font-size: 25px;");  // 生产录入控件使用18px字体
    largeInputStyle.replace("min-height: 35px;", "min-height: 40px;");  // 增加最小高度
    
    // 为生产录入页面的下拉框应用更大的字体
    ui->comboBox_entryEmployee->setStyleSheet(largeInputStyle);
    ui->dateEdit_entryDate->setStyleSheet(largeInputStyle);
    ui->pushButton_loadEmployee->setStyleSheet(primaryButtonStyle);
    
    // 为生产录入表格中的下拉框设置更大的字体
    // 这些会在运行时动态创建，所以我们需要在创建时设置
    
    // 设置下拉框选项字体大小的样式表
    QString comboBoxItemStyle = "QComboBox QAbstractItemView { font-size: 18px; }";
    qApp->setStyleSheet(qApp->styleSheet() + comboBoxItemStyle);
}

// 加载初始数据
void MainWindow::loadInitialData()
{
    // 使用分页加载函数替代原来的加载函数
    loadEmployeesWithPagination(0);
    loadToysWithPagination(0);
    loadDepartmentsWithPagination(0);
    loadEmployeeComboBoxes();
    loadToyComboBoxes();
    loadProcessesWithPagination(0); // 使用分页加载工序数据
}

// 加载员工数据
void MainWindow::loadEmployees()
{
    ui->tableWidget_employees->setRowCount(0);
    QSqlQuery query("SELECT employee_id, name, team, hire_date, contact, status FROM employees");
    int row = 0;
    while (query.next()) {
        ui->tableWidget_employees->insertRow(row);
        ui->tableWidget_employees->setItem(row, 0, new QTableWidgetItem(query.value(0).toString()));
        ui->tableWidget_employees->setItem(row, 1, new QTableWidgetItem(query.value(1).toString()));
        ui->tableWidget_employees->setItem(row, 2, new QTableWidgetItem(query.value(2).toString()));
        ui->tableWidget_employees->setItem(row, 3, new QTableWidgetItem(query.value(3).toString()));
        ui->tableWidget_employees->setItem(row, 4, new QTableWidgetItem(query.value(4).toString()));
        ui->tableWidget_employees->setItem(row, 5, new QTableWidgetItem(query.value(5).toString()));

        // 添加操作按钮
        QPushButton *editBtn = new QPushButton("编辑");
        editBtn->setStyleSheet("QPushButton { background-color: #3498db; color: white; border: none; padding: 4px 8px; border-radius: 2px; }");
        connect(editBtn, &QPushButton::clicked, [this, row]() {
            ui->tableWidget_employees->selectRow(row);
            onEditEmployee();
        });
        ui->tableWidget_employees->setCellWidget(row, 6, editBtn);

        row++;
    }
}

// 加载玩具数据 - 移除计件单价显示
void MainWindow::loadToys()
{
    ui->tableWidget_products->setRowCount(0);
    QSqlQuery query("SELECT toy_id, name, description FROM toys ORDER BY toy_id");
    int row = 0;
    while (query.next()) {
        ui->tableWidget_products->insertRow(row);
        ui->tableWidget_products->setItem(row, 0, new QTableWidgetItem(query.value(0).toString())); // 玩具编号
        ui->tableWidget_products->setItem(row, 1, new QTableWidgetItem(query.value(1).toString())); // 玩具名称
        ui->tableWidget_products->setItem(row, 2, new QTableWidgetItem(query.value(2).toString())); // 描述

        // 添加操作按钮
        QPushButton *editBtn = new QPushButton("编辑");
        editBtn->setStyleSheet("QPushButton { background-color: #3498db; color: white; border: none; padding: 4px 8px; border-radius: 2px; }");
        connect(editBtn, &QPushButton::clicked, [this, row]() {
            ui->tableWidget_products->selectRow(row);
            onEditToy();
        });
        ui->tableWidget_products->setCellWidget(row, 3, editBtn);

        row++;
    }
}

// 加载员工下拉框
void MainWindow::loadEmployeeComboBoxes()
{
    ui->comboBox_entryEmployee->clear();
    ui->comboBox_dailyReportEmployee->clear();
    ui->comboBox_monthlyReportEmployee->clear();
    ui->comboBox_wageEmployee->clear();
    ui->comboBox_statsDepartment->clear();

    // 修复：查询在职员工并按姓名排序
    QSqlQuery query("SELECT id, name, team FROM employees WHERE status = '在职' ORDER BY name");

    if (!executeQuery(query, "查询员工数据失败", this)) {
        return;
    }

    QStringList teamList;
    while (query.next()) {
        int id = query.value(0).toInt();
        QString name = query.value(1).toString();
        QString team = query.value(2).toString();

        // 修复：确保显示员工姓名而不是ID
        ui->comboBox_entryEmployee->addItem(name, id);
        ui->comboBox_dailyReportEmployee->addItem(name, id);
        ui->comboBox_monthlyReportEmployee->addItem(name, id);
        ui->comboBox_wageEmployee->addItem(name, id);

        // 收集班组信息
        if (!team.isEmpty() && !teamList.contains(team)) {
            teamList << team;
        }
    }

    // 添加班组到下拉框
    ui->comboBox_statsDepartment->addItem("全部");
    foreach (const QString &team, teamList) {
        ui->comboBox_statsDepartment->addItem(team);
    }

    // 设置默认选中第一个员工（如果有的话）
    if (ui->comboBox_entryEmployee->count() > 0) {
        ui->comboBox_entryEmployee->setCurrentIndex(0);
        // 自动加载第一个员工今天的数据
        loadTodayProductionData();
    }
}

// 加载玩具下拉框
void MainWindow::loadToyComboBoxes()
{
    // 由于生产录入表格中的玩具下拉框是动态创建的，这里只设置其他地方的玩具下拉框
}

// 连接信号和槽
void MainWindow::connectSignalsAndSlots()
{
    // 基础数据管理
    connect(ui->pushButton_addEmployee, &QPushButton::clicked, this, &MainWindow::onAddOrUpdateEmployee);
    connect(ui->pushButton_updateEmployee, &QPushButton::clicked, this, &MainWindow::onEditEmployee);
    connect(ui->pushButton_deleteEmployee, &QPushButton::clicked, this, &MainWindow::onDeleteEmployee);
    connect(ui->pushButton_addProduct, &QPushButton::clicked, this, &MainWindow::onAddToy);
    connect(ui->pushButton_updateProduct, &QPushButton::clicked, this, &MainWindow::onEditToy);
    connect(ui->pushButton_deleteProduct, &QPushButton::clicked, this, &MainWindow::onDeleteToy);

    // 搜索功能
    connect(ui->pushButton_searchEmployee, &QPushButton::clicked, this, &MainWindow::onSearchEmployee);
    connect(ui->pushButton_resetEmployee, &QPushButton::clicked, this, &MainWindow::onResetEmployee);
    connect(ui->pushButton_searchProduct, &QPushButton::clicked, this, &MainWindow::onSearchProduct);
    connect(ui->pushButton_resetProduct, &QPushButton::clicked, this, &MainWindow::onResetProduct);
    connect(ui->lineEdit_searchEmployee, &QLineEdit::returnPressed, this, &MainWindow::onSearchEmployee);
    connect(ui->lineEdit_searchProduct, &QLineEdit::returnPressed, this, &MainWindow::onSearchProduct);

    // 班组管理
    connect(ui->pushButton_addDepartment, &QPushButton::clicked, this, &MainWindow::onAddDepartment);
    connect(ui->pushButton_deleteDepartment, &QPushButton::clicked, this, &MainWindow::onDeleteDepartment);

    // 日常生产录入
    connect(ui->pushButton_addEntryRow, &QPushButton::clicked, this, &MainWindow::onAddProductionRow);
    connect(ui->pushButton_removeEntryRow, &QPushButton::clicked, this, &MainWindow::onRemoveProductionRow);
    connect(ui->pushButton_saveProductionData, &QPushButton::clicked, this, &MainWindow::onSaveProduction);
    connect(ui->pushButton_loadEmployee, &QPushButton::clicked, this, &MainWindow::loadTodayProductionData);

    // 员工下拉框变化事件 - 自动加载该员工今天的数据
    connect(ui->comboBox_entryEmployee, QOverload<int>::of(&QComboBox::currentIndexChanged), [this](int index) {
        if (index >= 0) {
            loadTodayProductionData();
        }
    });

    // 数据查询与统计
    connect(ui->pushButton_queryDailyReport, &QPushButton::clicked, this, &MainWindow::onGenerateDailyReport);
    connect(ui->pushButton_queryMonthlyReport, &QPushButton::clicked, this, &MainWindow::onGenerateMonthlyReport);
    connect(ui->pushButton_queryFactoryStats, &QPushButton::clicked, this, &MainWindow::onGenerateProductionStats);

    // 重置按钮
    connect(ui->pushButton_resetDailyReport, &QPushButton::clicked, this, &MainWindow::onResetDailyReport);
    connect(ui->pushButton_resetMonthlyReport, &QPushButton::clicked, this, &MainWindow::onResetMonthlyReport);
    connect(ui->pushButton_resetFactoryStats, &QPushButton::clicked, this, &MainWindow::onResetFactoryStats);
    connect(ui->pushButton_resetWage, &QPushButton::clicked, this, &MainWindow::onResetWage);

    // 工资核算
    connect(ui->pushButton_calculateWage, &QPushButton::clicked, this, &MainWindow::onCalculatePayroll);
    connect(ui->pushButton_systemSettings, &QPushButton::clicked, this, &MainWindow::onSystemSettings); // 新增：连接系统设置按钮
    connect(ui->pushButton_generateWageSlip, &QPushButton::clicked, this, &MainWindow::onGenerateWageSlip); // 修复：连接到正确的槽函数
    connect(ui->pushButton_exportWageDetails, &QPushButton::clicked, this, &MainWindow::onExportWageDetails); // 修复：连接到正确的槽函数
    connect(ui->pushButton_exportAllEmployeeWages, &QPushButton::clicked, this, &MainWindow::onExportAllEmployeeWages); // 新增：连接导出所有员工工资按钮

    // 通用功能
    connect(ui->pushButton_exportDailyReport, &QPushButton::clicked, this, &MainWindow::onExportData);
    connect(ui->pushButton_exportMonthlyReport, &QPushButton::clicked, this, &MainWindow::onExportData);
    connect(ui->pushButton_exportFactoryStats, &QPushButton::clicked, this, &MainWindow::onExportData);


    // 打印功能 - 新增
    connect(ui->pushButton_printDailyReport, &QPushButton::clicked, this, &MainWindow::onPrintData);
    connect(ui->pushButton_printMonthlyReport, &QPushButton::clicked, this, &MainWindow::onPrintData);
    connect(ui->pushButton_printFactoryStats, &QPushButton::clicked, this, &MainWindow::onPrintData);
    connect(ui->pushButton_printWageSlip, &QPushButton::clicked, this, &MainWindow::onPrintData);

    // 表格选择事件
    connect(ui->tableWidget_employees, &QTableWidget::itemSelectionChanged, this, &MainWindow::onEmployeeSelectionChanged);
    connect(ui->tableWidget_products, &QTableWidget::itemSelectionChanged, this, &MainWindow::onProductSelectionChanged);

    // 生产录入表格的数量编辑自动计算 - 优化版本
    connect(ui->tableWidget_productionEntry, &QTableWidget::itemChanged, [this](QTableWidgetItem *item) {
        // 只处理数量列（第4列）的变化
        if (item && item->column() == 3) {
            int row = item->row();

            // 验证输入的数量是否有效
            bool ok;
            int quantity = item->text().toInt(&ok);
            if (!ok || quantity < 0) {
                // 如果输入无效，恢复为1
                item->setText("1");
                quantity = 1;
            }

            // 更新该行的小计
            updateRowSubtotal(row);
        }
    });

    // 添加报表表格的查看详情功能
    // (已移除月报查看详情功能)

    connect(ui->tableWidget_factoryStats, &QTableWidget::cellClicked, [this](int row, int column) {

        if (column == 5) { // 操作列
            QString productInfo = ui->tableWidget_factoryStats->item(row, 1)->text();
            if (productInfo != "--") {
                // 获取统计类型
                QString statsType = ui->comboBox_statsType->currentText();
                QString period = ui->comboBox_statsPeriod->currentText();
                QString team = ui->comboBox_statsDepartment->currentText();
                
                // 根据统计周期确定日期范围
                QDate today = QDate::currentDate();
                QString startDate, endDate;

                if (period == "按日") {
                    // 获取表格中显示的日期
                    QTableWidgetItem *dateItem = ui->tableWidget_factoryStats->item(row, 0);
                    if (dateItem) {
                        QString dateStr = dateItem->text();
                        QDate specificDate = QDate::fromString(dateStr, "yyyy-MM-dd");
                        if (specificDate.isValid()) {
                            startDate = specificDate.toString("yyyy-MM-dd");
                            endDate = specificDate.toString("yyyy-MM-dd");
                        } else {
                            startDate = today.toString("yyyy-MM-dd");
                            endDate = today.toString("yyyy-MM-dd");
                        }
                    } else {
                        startDate = today.toString("yyyy-MM-dd");
                        endDate = today.toString("yyyy-MM-dd");
                    }
                } else if (period == "按周") {
                    // 获取表格中显示的日期并计算周范围
                    QTableWidgetItem *dateItem = ui->tableWidget_factoryStats->item(row, 0);
                    if (dateItem) {
                        QString dateStr = dateItem->text();
                        QDate specificDate = QDate::fromString(dateStr, "yyyy-MM-dd");
                        if (specificDate.isValid()) {
                            startDate = specificDate.addDays(-specificDate.dayOfWeek() + 1).toString("yyyy-MM-dd"); // 该周周一
                            endDate = specificDate.toString("yyyy-MM-dd");
                        } else {
                            startDate = today.addDays(-today.dayOfWeek() + 1).toString("yyyy-MM-dd"); // 本周一
                            endDate = today.toString("yyyy-MM-dd");
                        }
                    } else {
                        startDate = today.addDays(-today.dayOfWeek() + 1).toString("yyyy-MM-dd"); // 本周一
                        endDate = today.toString("yyyy-MM-dd");
                    }
                } else { // 按月
                    // 使用与主查询相同的日期范围逻辑
                    // 获取用户选择的结束日期
                    QDate selectedEndDate = ui->dateEdit_statsEndDate->date();
                    // 开始日期为结束日期往前推一个月
                    startDate = selectedEndDate.addMonths(-1).toString("yyyy-MM-dd");
                    // 结束日期为用户选择的日期
                    endDate = selectedEndDate.toString("yyyy-MM-dd");
                }
                
                // 显示详细统计信息
                showFactoryStatsDetails(productInfo, statsType, team, startDate, endDate);
            }
        }
    });
    
    // 连接最近生产记录分页信号和槽
    connect(ui->pushButton_firstPageRecentActivity, &QPushButton::clicked, [this]() {
        onRecentActivityPageChanged(0);
    });
    connect(ui->pushButton_prevPageRecentActivity, &QPushButton::clicked, [this]() {
        if (currentRecentActivityPage > 0) {
            onRecentActivityPageChanged(currentRecentActivityPage - 1);
        }
    });
    connect(ui->pushButton_nextPageRecentActivity, &QPushButton::clicked, [this]() {
        if (currentRecentActivityPage < totalRecentActivityPages - 1) {
            onRecentActivityPageChanged(currentRecentActivityPage + 1);
        }
    });
    connect(ui->pushButton_lastPageRecentActivity, &QPushButton::clicked, [this]() {
        onRecentActivityPageChanged(totalRecentActivityPages - 1);
    });
    
    // 连接员工管理分页信号和槽
    connect(ui->pushButton_firstPageEmployee, &QPushButton::clicked, [this]() {
        onEmployeePageChanged(0);
    });
    connect(ui->pushButton_prevPageEmployee, &QPushButton::clicked, [this]() {
        if (currentEmployeePage > 0) {
            onEmployeePageChanged(currentEmployeePage - 1);
        }
    });
    connect(ui->pushButton_nextPageEmployee, &QPushButton::clicked, [this]() {
        int totalPages = (totalEmployeeRecords + itemsPerPage - 1) / itemsPerPage;
        if (currentEmployeePage < totalPages - 1) {
            onEmployeePageChanged(currentEmployeePage + 1);
        }
    });
    connect(ui->pushButton_lastPageEmployee, &QPushButton::clicked, [this]() {
        int totalPages = (totalEmployeeRecords + itemsPerPage - 1) / itemsPerPage;
        if (totalPages > 0) {
            onEmployeePageChanged(totalPages - 1);
        }
    });
    
    // 连接产品管理分页信号和槽
    connect(ui->pushButton_firstPageProduct, &QPushButton::clicked, [this]() {
        onToyPageChanged(0);
    });
    connect(ui->pushButton_prevPageProduct, &QPushButton::clicked, [this]() {
        if (currentToyPage > 0) {
            onToyPageChanged(currentToyPage - 1);
        }
    });
    connect(ui->pushButton_nextPageProduct, &QPushButton::clicked, [this]() {
        int totalPages = (totalToyRecords + itemsPerPage - 1) / itemsPerPage;
        if (currentToyPage < totalPages - 1) {
            onToyPageChanged(currentToyPage + 1);
        }
    });
    connect(ui->pushButton_lastPageProduct, &QPushButton::clicked, [this]() {
        int totalPages = (totalToyRecords + itemsPerPage - 1) / itemsPerPage;
        if (totalPages > 0) {
            onToyPageChanged(totalPages - 1);
        }
    });
    
    // 连接班组管理分页信号和槽
    connect(ui->pushButton_firstPageDepartment, &QPushButton::clicked, [this]() {
        onDepartmentPageChanged(0);
    });
    connect(ui->pushButton_prevPageDepartment, &QPushButton::clicked, [this]() {
        if (currentDeptPage > 0) {
            onDepartmentPageChanged(currentDeptPage - 1);
        }
    });
    connect(ui->pushButton_nextPageDepartment, &QPushButton::clicked, [this]() {
        int totalPages = (totalDeptRecords + itemsPerPage - 1) / itemsPerPage;
        if (currentDeptPage < totalPages - 1) {
            onDepartmentPageChanged(currentDeptPage + 1);
        }
    });
    connect(ui->pushButton_lastPageDepartment, &QPushButton::clicked, [this]() {
        int totalPages = (totalDeptRecords + itemsPerPage - 1) / itemsPerPage;
        onDepartmentPageChanged(totalPages - 1);
    });
    
    // 连接员工日报表分页信号和槽
    connect(ui->pushButton_firstPageDailyReport, &QPushButton::clicked, [this]() {
        onDailyReportPageChanged(0);
    });
    connect(ui->pushButton_prevPageDailyReport, &QPushButton::clicked, [this]() {
        if (currentDailyReportPage > 0) {
            onDailyReportPageChanged(currentDailyReportPage - 1);
        }
    });
    connect(ui->pushButton_nextPageDailyReport, &QPushButton::clicked, [this]() {
        int totalPages = (totalDailyReportRecords + itemsPerPage - 1) / itemsPerPage;
        if (totalPages == 0) totalPages = 1;
        if (currentDailyReportPage < totalPages - 1) {
            onDailyReportPageChanged(currentDailyReportPage + 1);
        }
    });
    connect(ui->pushButton_lastPageDailyReport, &QPushButton::clicked, [this]() {
        int totalPages = (totalDailyReportRecords + itemsPerPage - 1) / itemsPerPage;
        if (totalPages == 0) totalPages = 1;
        onDailyReportPageChanged(totalPages - 1);
    });
    
    // 连接员工月报表分页信号和槽
    connect(ui->pushButton_firstPageMonthlyReport, &QPushButton::clicked, [this]() {
        onMonthlyReportPageChanged(0);
    });
    connect(ui->pushButton_prevPageMonthlyReport, &QPushButton::clicked, [this]() {
        if (currentMonthlyReportPage > 0) {
            onMonthlyReportPageChanged(currentMonthlyReportPage - 1);
        }
    });
    connect(ui->pushButton_nextPageMonthlyReport, &QPushButton::clicked, [this]() {
        int totalPages = (totalMonthlyReportRecords + itemsPerPage - 1) / itemsPerPage;
        if (totalPages == 0) totalPages = 1;
        if (currentMonthlyReportPage < totalPages - 1) {
            onMonthlyReportPageChanged(currentMonthlyReportPage + 1);
        }
    });
    connect(ui->pushButton_lastPageMonthlyReport, &QPushButton::clicked, [this]() {
        int totalPages = (totalMonthlyReportRecords + itemsPerPage - 1) / itemsPerPage;
        if (totalPages == 0) totalPages = 1;
        onMonthlyReportPageChanged(totalPages - 1);
    });
    
    // 连接全厂/班组产量统计分页信号和槽
    connect(ui->pushButton_firstPageFactoryStats, &QPushButton::clicked, [this]() {
        onFactoryStatsPageChanged(0);
    });
    connect(ui->pushButton_prevPageFactoryStats, &QPushButton::clicked, [this]() {
        if (currentFactoryStatsPage > 0) {
            onFactoryStatsPageChanged(currentFactoryStatsPage - 1);
        }
    });
    connect(ui->pushButton_nextPageFactoryStats, &QPushButton::clicked, [this]() {
        int totalPages = (totalFactoryStatsRecords + itemsPerPage - 1) / itemsPerPage;
        if (totalPages == 0) totalPages = 1;
        if (currentFactoryStatsPage < totalPages - 1) {
            onFactoryStatsPageChanged(currentFactoryStatsPage + 1);
        }
    });
    connect(ui->pushButton_lastPageFactoryStats, &QPushButton::clicked, [this]() {
        int totalPages = (totalFactoryStatsRecords + itemsPerPage - 1) / itemsPerPage;
        if (totalPages == 0) totalPages = 1;
        if (totalPages > 0) {  // 添加检查确保 totalPages > 0
            onFactoryStatsPageChanged(totalPages - 1);
        }
    });
    
    // 连接统计周期选择控件变化事件
    connect(ui->comboBox_statsPeriod, &QComboBox::currentTextChanged, [this](const QString &text) {
        // 根据选择的统计周期显示或隐藏日期选择控件
        if (text == "按月") {
            // 显示结束日期标签和控件
            ui->label_statsEndDate->setVisible(true);
            ui->dateEdit_statsEndDate->setVisible(true);
            // 设置默认日期为当前日期
            ui->dateEdit_statsEndDate->setDate(QDate::currentDate());
        } else {
            // 隐藏结束日期标签和控件
            ui->label_statsEndDate->setVisible(false);
            ui->dateEdit_statsEndDate->setVisible(false);
        }
    });
}

// 员工日报表分页槽函数
void MainWindow::onDailyReportPageChanged(int page)
{
    currentDailyReportPage = page;
    // 重新执行查询并显示指定页的数据
    onGenerateDailyReport();
}

// 员工月报表分页槽函数
void MainWindow::onMonthlyReportPageChanged(int page)
{
    currentMonthlyReportPage = page;
    // 重新执行查询并显示指定页的数据
    onGenerateMonthlyReport();
}

// 全厂/班组产量统计分页槽函数
void MainWindow::onFactoryStatsPageChanged(int page)
{
    currentFactoryStatsPage = page;
    // 重新执行查询并显示指定页的数据
    onGenerateProductionStats();
}

// 更新仪表盘
void MainWindow::updateDashboard()
{
    // 使用 QTimer 延迟执行更新操作，避免界面卡顿
    QTimer::singleShot(0, this, [this]() {
        QSqlQuery query;

        // 获取今日总产量（支持工序维度）
        QString today = QDate::currentDate().toString("yyyy-MM-dd");
        query.prepare("SELECT SUM(quantity) FROM production WHERE date = ?");
        query.addBindValue(today);
        int totalToday = 0;
        if (executeQuery(query, "查询今日总产量失败", this) && query.next()) {
            totalToday = query.value(0).toInt();
        }

        // 获取新版本表的产量数据
        QSqlQuery v2Query;
        v2Query.prepare("SELECT SUM(quantity) FROM production_v2 WHERE date = ?");
        v2Query.addBindValue(today);
        int totalTodayV2 = 0;
        if (executeQuery(v2Query, "查询今日总产量(新版本)失败", this) && v2Query.next()) {
            totalTodayV2 = v2Query.value(0).toInt();
        }

        // 显示总产量（两个表的合计）
        ui->todayProductionLabel->setText(QString("今日总产量：%1 件").arg(totalToday + totalTodayV2));

        // 获取今日总产值（支持工序维度）
        query.prepare("SELECT SUM(p.quantity * t.piece_rate) FROM production p JOIN toys t ON p.toy_id = t.id WHERE p.date = ?");
        query.addBindValue(today);
        double totalRevenue = 0.0;
        if (executeQuery(query, "查询今日总产值失败", this) && query.next()) {
            totalRevenue = query.value(0).toDouble();
        }

        // 获取新版本表的产值数据
        v2Query.prepare("SELECT SUM(subtotal) FROM production_v2 WHERE date = ?");
        v2Query.addBindValue(today);
        double totalRevenueV2 = 0.0;
        if (executeQuery(v2Query, "查询今日总产值(新版本)失败", this) && v2Query.next()) {
            totalRevenueV2 = v2Query.value(0).toDouble();
        }

        // 显示总产值（两个表的合计）
        ui->todayRevenueLabel->setText(QString("今日总产值：%1 元").arg(QString::number(totalRevenue + totalRevenueV2, 'f', 3)));

        // 获取员工总数
        query.prepare("SELECT COUNT(*) FROM employees WHERE status = '在职'");
        int employeeCount = 0;
        if (executeQuery(query, "查询员工总数失败", this) && query.next()) {
            employeeCount = query.value(0).toInt();
        }
        ui->totalEmployeeLabel->setText(QString("员工总数：%1 人").arg(employeeCount));

        // 获取今日出勤人数（有生产记录的员工）
        query.prepare("SELECT COUNT(DISTINCT employee_id) FROM production WHERE date = ?");
        query.addBindValue(today);
        int presentCount = 0;
        if (executeQuery(query, "查询今日出勤人数失败", this) && query.next()) {
            presentCount = query.value(0).toInt();
        }

        // 获取新版本表的出勤人数
        v2Query.prepare("SELECT COUNT(DISTINCT employee_id) FROM production_v2 WHERE date = ?");
        v2Query.addBindValue(today);
        int presentCountV2 = 0;
        if (executeQuery(v2Query, "查询今日出勤人数(新版本)失败", this) && v2Query.next()) {
            presentCountV2 = v2Query.value(0).toInt();
        }

        // 显示出勤人数（两个表的合计）
        ui->presentEmployeeLabel->setText(QString("今日出勤：%1 人").arg(presentCount + presentCountV2));

        // 获取玩具种类数
        query.prepare("SELECT COUNT(*) FROM toys");
        int toyCount = 0;
        if (executeQuery(query, "查询玩具种类数失败", this) && query.next()) {
            toyCount = query.value(0).toInt();
        }
        ui->productCountLabel->setText(QString("玩具种类数：%1 种").arg(toyCount));

        // 获取今日产量最高的玩具（支持工序维度）
        query.prepare("SELECT t.name, SUM(p.quantity) as total FROM production p JOIN toys t ON p.toy_id = t.id WHERE p.date = ? GROUP BY t.name ORDER BY total DESC LIMIT 1");
        query.addBindValue(today);
        QString topProduct = "--";
        if (executeQuery(query, "查询今日产量最高玩具失败", this) && query.next()) {
            QString productName = query.value(0).toString();
            int quantity = query.value(1).toInt();
            topProduct = QString("%1(%2件)").arg(productName).arg(quantity);
        }

        // 检查新版本表中是否有更高的产量
        v2Query.prepare("SELECT t.name, p.name as process_name, SUM(pv2.quantity) as total "
                       "FROM production_v2 pv2 "
                       "JOIN toys t ON pv2.toy_id = t.id "
                       "JOIN processes p ON pv2.process_id = p.id "
                       "WHERE pv2.date = ? "
                       "GROUP BY t.name, p.name "
                       "ORDER BY total DESC LIMIT 1");
        v2Query.addBindValue(today);
        if (executeQuery(v2Query, "查询今日产量最高玩具(新版本)失败", this) && v2Query.next()) {
            QString productName = v2Query.value(0).toString();
            QString processName = v2Query.value(1).toString();
            int quantity = v2Query.value(2).toInt();
            QString v2TopProduct = QString("%1-%2(%3件)").arg(productName).arg(processName).arg(quantity);

            // 如果新版本的产量更高，则更新显示
            if (quantity > (topProduct.contains("(") ? topProduct.mid(topProduct.indexOf("(") + 1, topProduct.indexOf("件") - topProduct.indexOf("(") - 1).toInt() : 0)) {
                topProduct = v2TopProduct;
            }
        }

        ui->topProductLabel->setText(QString("今日产量最高：%1").arg(topProduct));

        // 加载最近生产记录的第一页数据
        loadRecentActivityWithPagination(0);
    });
}

// 添加员工
void MainWindow::onAddEmployee()
{
    EmployeeDialog dialog(this);
    dialog.setEditMode(false);

    if (dialog.exec() == QDialog::Accepted) {
        QString employeeId = dialog.getEmployeeId();
        QString name = dialog.getName();
        QString team = dialog.getTeam();
        QString hireDate = dialog.getHireDate();
        QString contact = dialog.getContact();
        QString status = dialog.getStatus();

        qDebug() << "准备添加员工:";
        qDebug() << "  员工编号:" << employeeId;
        qDebug() << "  姓名:" << name;
        qDebug() << "  班组:" << team;
        qDebug() << "  入职日期:" << hireDate;
        qDebug() << "  联系方式:" << contact;
        qDebug() << "  状态:" << status;

        // 检查员工编号是否已存在
        QSqlQuery checkQuery;
        checkQuery.prepare("SELECT COUNT(*) FROM employees WHERE employee_id = ?");
        checkQuery.addBindValue(employeeId);
        if (executeQuery(checkQuery, "检查员工编号是否存在失败", this) && checkQuery.next()) {
            if (checkQuery.value(0).toInt() > 0) {
                QMessageBox::warning(this, "错误", "员工编号已存在，请使用其他编号");
                return;
            }
        }

        QSqlQuery query;
        query.prepare("INSERT INTO employees (employee_id, name, team, hire_date, contact, status) VALUES (?, ?, ?, ?, ?, ?)");
        query.addBindValue(employeeId);
        query.addBindValue(name);
        query.addBindValue(team);
        query.addBindValue(hireDate);
        query.addBindValue(contact);
        query.addBindValue(status);

        qDebug() << "执行SQL语句:" << query.lastQuery();
        qDebug() << "绑定的参数:";
        qDebug() << "  1:" << employeeId;
        qDebug() << "  2:" << name;
        qDebug() << "  3:" << team;
        qDebug() << "  4:" << hireDate;
        qDebug() << "  5:" << contact;
        qDebug() << "  6:" << status;

        if (executeQuery(query, "添加员工失败", this)) {
            QMessageBox::information(this, "成功", "员工添加成功");
            // 使用分页加载员工数据
            loadEmployeesWithPagination(currentEmployeePage);
        } else {
            // 显示更详细的错误信息
            QString detailedError = QString("添加员工失败:\n错误信息: %1\nSQL语句: %2")
                .arg(query.lastError().text())
                .arg(query.lastQuery());
            QMessageBox::critical(this, "数据库错误", detailedError);
            qCritical() << detailedError;
        }
    }
}

// 编辑员工

// 最近生产记录分页槽函数
void MainWindow::onRecentActivityPageChanged(int page)
{
    currentRecentActivityPage = page;
    loadRecentActivityWithPagination(page);
}

// 加载最近生产记录分页数据
void MainWindow::loadRecentActivityWithPagination(int page)
{
    // 计算偏移量
    int offset = page * itemsPerPage;
    
    // 计算最近40天的日期范围
    QString endDate = QDate::currentDate().toString("yyyy-MM-dd");
    QString startDate = QDate::currentDate().addDays(-39).toString("yyyy-MM-dd");
    
    // 查询最近40天的生产记录总数
    QSqlQuery countQuery;
    countQuery.prepare("SELECT COUNT(*) FROM ("
                      "SELECT 1 FROM production p WHERE p.date BETWEEN ? AND ? "
                      "UNION ALL "
                      "SELECT 1 FROM production_v2 pv2 WHERE pv2.date BETWEEN ? AND ?"
                      ") AS combined_records");
    countQuery.addBindValue(startDate);
    countQuery.addBindValue(endDate);
    countQuery.addBindValue(startDate);
    countQuery.addBindValue(endDate);
    
    int totalRecords = 0;
    if (executeQuery(countQuery, "查询最近生产记录总数失败", this) && countQuery.next()) {
        totalRecords = countQuery.value(0).toInt();
    }
    
    // 计算总页数
    totalRecentActivityPages = (totalRecords + itemsPerPage - 1) / itemsPerPage;
    if (totalRecentActivityPages == 0) totalRecentActivityPages = 1;
    
    // 清空表格
    ui->recentActivityTable->setRowCount(0);
    
    // 查询最近40天的生产记录 - 支持工序维度，带分页
    // 按照工序名称和日期排序
    QSqlQuery query;
    query.prepare("SELECT * FROM ("
                  "SELECT p.date, e.name, t.name, '' as process_name, p.quantity, (p.quantity * t.piece_rate) AS amount "
                  "FROM production p "
                  "JOIN employees e ON p.employee_id = e.id "
                  "JOIN toys t ON p.toy_id = t.id "
                  "WHERE p.date BETWEEN ? AND ? "
                  "UNION ALL "
                  "SELECT pv2.date, e.name, t.name, p.name as process_name, pv2.quantity, pv2.subtotal AS amount "
                  "FROM production_v2 pv2 "
                  "JOIN employees e ON pv2.employee_id = e.id "
                  "JOIN toys t ON pv2.toy_id = t.id "
                  "JOIN processes p ON pv2.process_id = p.id "
                  "WHERE pv2.date BETWEEN ? AND ? "
                  ") AS combined_results "
                  "ORDER BY process_name ASC, date DESC "
                  "LIMIT ? OFFSET ?");
    
    // 为第一个子查询绑定参数
    query.addBindValue(startDate);
    query.addBindValue(endDate);
    // 为第二个子查询绑定参数
    query.addBindValue(startDate);
    query.addBindValue(endDate);
    // 为LIMIT和OFFSET绑定参数
    query.addBindValue(itemsPerPage);
    query.addBindValue(offset);
    
    QList<QStringList> recentRecords;
    
    if (executeQuery(query, "查询最近生产记录分页数据失败", this)) {
        while (query.next()) {
            QStringList record;
            record << query.value(0).toString()  // 日期
                   << query.value(1).toString()  // 员工姓名
                   << query.value(2).toString()  // 玩具名称
                   << query.value(3).toString()  // 工序名称
                   << query.value(4).toString()  // 数量
                   << QString::number(query.value(5).toDouble(), 'f', 3); // 金额
            recentRecords.append(record);
        }
    }
    
    // 显示当前页的记录
    for (const QStringList &record : recentRecords) {
        int row = ui->recentActivityTable->rowCount();
        ui->recentActivityTable->insertRow(row);
        
        // 确保数据正确显示
        QString date = record[0];
        QString employeeName = record[1];
        QString toyName = record[2];
        QString processName = record[3];
        QString quantity = record[4];
        QString amount = record[5];
        
        // 插入数据到表格
        ui->recentActivityTable->setItem(row, 0, new QTableWidgetItem(date));
        ui->recentActivityTable->setItem(row, 1, new QTableWidgetItem(employeeName));
        ui->recentActivityTable->setItem(row, 2, new QTableWidgetItem(toyName));
        ui->recentActivityTable->setItem(row, 3, new QTableWidgetItem(processName));
        ui->recentActivityTable->setItem(row, 4, new QTableWidgetItem(quantity));
        ui->recentActivityTable->setItem(row, 5, new QTableWidgetItem(amount));
    }
    
    // 更新分页控件
    updatePaginationControls("recentActivityTable", page, totalRecentActivityPages);
}

void MainWindow::onEditEmployee()
{
    int currentRow = ui->tableWidget_employees->currentRow();
    if (currentRow < 0) {
        QMessageBox::warning(this, "警告", "请先选择要编辑的员工");
        return;
    }

    // 获取当前员工数据
    QString employeeId = ui->tableWidget_employees->item(currentRow, 0)->text();
    QString currentName = ui->tableWidget_employees->item(currentRow, 1)->text();
    QString currentTeam = ui->tableWidget_employees->item(currentRow, 2)->text();
    QString currentHireDate = ui->tableWidget_employees->item(currentRow, 3)->text();
    QString currentContact = ui->tableWidget_employees->item(currentRow, 4)->text();
    QString currentStatus = ui->tableWidget_employees->item(currentRow, 5)->text();

    // 创建编辑对话框
    EmployeeDialog dialog(this);
    dialog.setEditMode(true);
    dialog.setEmployeeData(employeeId, currentName, currentTeam, currentHireDate, currentContact, currentStatus);

    if (dialog.exec() == QDialog::Accepted) {
        QString name = dialog.getName();
        QString team = dialog.getTeam();
        QString hireDate = dialog.getHireDate();
        QString contact = dialog.getContact();
        QString status = dialog.getStatus();

        QSqlQuery query;
        query.prepare("UPDATE employees SET name = ?, team = ?, hire_date = ?, contact = ?, status = ? WHERE employee_id = ?");
        query.addBindValue(name);
        query.addBindValue(team);
        query.addBindValue(hireDate);
        query.addBindValue(contact);
        query.addBindValue(status);
        query.addBindValue(employeeId);

        if (executeQuery(query, "更新员工信息失败", this)) {
            QMessageBox::information(this, "成功", "员工信息更新成功");
            // 使用分页加载员工数据
            loadEmployeesWithPagination(currentEmployeePage);
        }
    }
}

// 删除员工
void MainWindow::onDeleteEmployee()
{
    int currentRow = ui->tableWidget_employees->currentRow();
    if (currentRow < 0) {
        QMessageBox::warning(this, "警告", "请先选择要删除的员工");
        return;
    }

    QString employeeId = ui->tableWidget_employees->item(currentRow, 0)->text();
    QString name = ui->tableWidget_employees->item(currentRow, 1)->text();

    if (QMessageBox::question(this, "确认删除", "确定要删除员工 " + name + " 吗？") == QMessageBox::Yes) {
        QSqlQuery query;
        query.prepare("DELETE FROM employees WHERE employee_id = ?");
        query.addBindValue(employeeId);

        if (executeQuery(query, "删除员工失败", this)) {
            QMessageBox::information(this, "成功", "员工删除成功");
            // 使用分页加载员工数据
            loadEmployeesWithPagination(currentEmployeePage);
        } else {
            QMessageBox::critical(this, "错误", "员工删除失败: " + query.lastError().text());
        }
    }
}

// 刷新员工相关数据的统一接口
void MainWindow::refreshEmployeeData()
{
    loadEmployees();
    loadEmployeeComboBoxes();
    updateDashboard();
}

// 添加玩具
void MainWindow::onAddToy()
{
    ToyDialog dialog(this);
    dialog.setEditMode(false);

    if (dialog.exec() == QDialog::Accepted) {
        QString toyId = dialog.getToyId();
        QString name = dialog.getName();
        QString description = dialog.getDescription();
        QList<int> processIds = dialog.getSelectedProcessIds();

        // 检查玩具编号是否已存在
        QSqlQuery checkQuery;
        checkQuery.prepare("SELECT COUNT(*) FROM toys WHERE toy_id = ?");
        checkQuery.addBindValue(toyId);
        if (executeQuery(checkQuery, "检查玩具编号是否存在失败", this) && checkQuery.next()) {
            if (checkQuery.value(0).toInt() > 0) {
                QMessageBox::warning(this, "错误", "玩具编号已存在，请使用其他编号");
                return;
            }
        }

        if (processIds.isEmpty()) {
            QMessageBox::warning(this, "错误", "请至少选择一个工序");
            return;
        }

        // 开始事务
        if (!beginTransaction(db, "添加玩具时开启事务失败", this)) {
            return;
        }

        // 插入玩具信息，设置piece_rate为默认值0.0
        QSqlQuery toyQuery;
        toyQuery.prepare("INSERT INTO toys (toy_id, name, description, piece_rate) VALUES (?, ?, ?, ?)");
        toyQuery.addBindValue(toyId);
        toyQuery.addBindValue(name);
        toyQuery.addBindValue(description);
        toyQuery.addBindValue(0.0); // 默认计件单价为0.0

        if (!executeQuery(toyQuery, "添加玩具失败", this)) {
            db.rollback();
            return;
        }

        // 获取新插入的玩具ID
        int dbToyId = toyQuery.lastInsertId().toInt();

        // 插入玩具-工序关联关系
        QSqlQuery relationQuery;
        relationQuery.prepare("INSERT INTO toy_processes (toy_id, process_id) VALUES (?, ?)");

        for (int processId : processIds) {
            relationQuery.addBindValue(dbToyId);
            relationQuery.addBindValue(processId);

            if (!executeQuery(relationQuery, "添加玩具工序关联失败", this)) {
                db.rollback();
                return;
            }
        }

        // 提交事务
        if (!db.commit()) {
            QMessageBox::critical(this, "错误", "提交事务失败: " + db.lastError().text());
            db.rollback();
            return;
        }

        QMessageBox::information(this, "成功", "玩具添加成功");
        loadToysWithPagination(currentToyPage);  // 使用分页加载
        updateDashboard();
    }
}

// 编辑玩具
void MainWindow::onEditToy()
{
    int currentRow = ui->tableWidget_products->currentRow();
    if (currentRow < 0) {
        QMessageBox::warning(this, "警告", "请先选择要编辑的玩具");
        return;
    }

    // 获取当前玩具数据
    QString toyId = ui->tableWidget_products->item(currentRow, 0)->text();
    QString currentName = ui->tableWidget_products->item(currentRow, 1)->text();
    QString currentDescription = ui->tableWidget_products->item(currentRow, 2)->text();

    // 查询玩具的数据库ID和关联工序
    QSqlQuery toyQuery;
    toyQuery.prepare("SELECT id FROM toys WHERE toy_id = ?");
    toyQuery.addBindValue(toyId);

    QList<int> currentProcessIds;
    if (executeQuery(toyQuery, "查询玩具信息失败", this) && toyQuery.next()) {
        int dbToyId = toyQuery.value(0).toInt();

        // 查询玩具的关联工序
        QSqlQuery processQuery;
        processQuery.prepare("SELECT process_id FROM toy_processes WHERE toy_id = ?");
        processQuery.addBindValue(dbToyId);

        if (executeQuery(processQuery, "查询玩具工序关联失败", this)) {
            while (processQuery.next()) {
                currentProcessIds << processQuery.value(0).toInt();
            }
        }
    } else {
        QMessageBox::warning(this, "错误", "无法找到玩具信息");
        return;
    }

    // 创建编辑对话框
    ToyDialog dialog(this);
    dialog.setEditMode(true);
    dialog.setToyData(toyId, currentName, currentDescription, currentProcessIds);

    if (dialog.exec() == QDialog::Accepted) {
        QString name = dialog.getName();
        QString description = dialog.getDescription();
        QList<int> processIds = dialog.getSelectedProcessIds();

        if (processIds.isEmpty()) {
            QMessageBox::warning(this, "错误", "请至少选择一个工序");
            return;
        }

        // 开始事务
        if (!beginTransaction(db, "更新玩具时开启事务失败", this)) {
            return;
        }

        // 更新玩具信息
        QSqlQuery updateToyQuery;
        updateToyQuery.prepare("UPDATE toys SET name = ?, description = ? WHERE toy_id = ?");
        updateToyQuery.addBindValue(name);
        updateToyQuery.addBindValue(description);
        updateToyQuery.addBindValue(toyId);

        if (!executeQuery(updateToyQuery, "更新玩具信息失败", this)) {
            db.rollback();
            return;
        }

        // 获取玩具的数据库ID
        QSqlQuery idQuery;
        idQuery.prepare("SELECT id FROM toys WHERE toy_id = ?");
        idQuery.addBindValue(toyId);

        if (!executeQuery(idQuery, "查询玩具ID失败", this) || !idQuery.next()) {
            db.rollback();
            return;
        }

        int dbToyId = idQuery.value(0).toInt();

        // 删除现有的工序关联
        QSqlQuery deleteQuery;
        deleteQuery.prepare("DELETE FROM toy_processes WHERE toy_id = ?");
        deleteQuery.addBindValue(dbToyId);

        if (!executeQuery(deleteQuery, "删除玩具工序关联失败", this)) {
            db.rollback();
            return;
        }

        // 插入新的工序关联
        QSqlQuery relationQuery;
        relationQuery.prepare("INSERT INTO toy_processes (toy_id, process_id) VALUES (?, ?)");

        for (int processId : processIds) {
            relationQuery.addBindValue(dbToyId);
            relationQuery.addBindValue(processId);

            if (!executeQuery(relationQuery, "添加玩具工序关联失败", this)) {
                db.rollback();
                return;
            }
        }

        // 提交事务
        if (!db.commit()) {
            QMessageBox::critical(this, "错误", "提交事务失败: " + db.lastError().text());
            db.rollback();
            return;
        }

        QMessageBox::information(this, "成功", "玩具更新成功");
        loadToysWithPagination(currentToyPage);  // 使用分页加载
        updateDashboard();
    }
}

// 加载今日生产数据
void MainWindow::loadTodayProductionData()
{
    int employeeId = ui->comboBox_entryEmployee->currentData().toInt();
    QString date = ui->dateEdit_entryDate->date().toString("yyyy-MM-dd");

    // 清空现有数据
    ui->tableWidget_productionEntry->setRowCount(0);

    // 查询该员工当天的生产记录（新版本表，包含工序信息）
    QSqlQuery query;
    query.prepare("SELECT pv2.toy_id, pv2.process_id, pv2.quantity "
                 "FROM production_v2 pv2 "
                 "WHERE pv2.employee_id = ? AND pv2.date = ?");
    query.addBindValue(employeeId);
    query.addBindValue(date);

    if (!executeQuery(query, "查询生产记录失败", this)) {
        return;
    }

    while (query.next()) {
        int toyId = query.value(0).toInt();
        int processId = query.value(1).toInt();
        int quantity = query.value(2).toInt();

        // 添加一行并填充数据
        int row = ui->tableWidget_productionEntry->rowCount();
        ui->tableWidget_productionEntry->insertRow(row);
        ui->tableWidget_productionEntry->setRowHeight(row, 60);  // 增加行高到60

        // 第1列：玩具产品下拉框
        QComboBox *toyComboBox = new QComboBox();
        toyComboBox->setObjectName(QString("toyComboBox_%1").arg(row));
        toyComboBox->setMinimumHeight(40);  // 增加最小高度到40
        toyComboBox->setStyleSheet("QComboBox { font-size: 16px; min-height: 40px; }"
                               "QComboBox QAbstractItemView { font-size: 18px; min-height: 30px; }");  // 设置更大的字体

        // 使用优化后的函数加载玩具数据
        loadToyDataIntoComboBox(toyComboBox);

        ui->tableWidget_productionEntry->setCellWidget(row, 0, toyComboBox);

        // 第2列：工序下拉框
        QComboBox *processComboBox = new QComboBox();
        processComboBox->setObjectName(QString("processComboBox_%1").arg(row));
        processComboBox->setMinimumHeight(40);  // 增加最小高度到40
        processComboBox->setStyleSheet("QComboBox { font-size: 16px; min-height: 40px; }"
                                   "QComboBox QAbstractItemView { font-size: 18px; min-height: 30px; }");  // 设置更大的字体
        ui->tableWidget_productionEntry->setCellWidget(row, 1, processComboBox);

        // 设置当前玩具选中项
        int toyIndex = toyComboBox->findData(toyId);
        if (toyIndex >= 0) {
            toyComboBox->setCurrentIndex(toyIndex);
        }

        // 连接玩具选择变化信号，更新工序列表
        connect(toyComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), [this, toyComboBox, processComboBox](int index) {
            if (index < 0) return;

            int toyId = toyComboBox->currentData().toInt();
            
            // 使用优化后的函数更新工序列表
            updateProcessListForToy(toyComboBox, processComboBox, toyId);
            
            // 如果工序列表不为空，自动选择第一个工序（除了提示项）
            if (processComboBox->count() > 1) {
                processComboBox->setCurrentIndex(1);
                
                // 直接更新计件单价，而不是通过信号触发
                int processId = processComboBox->currentData().toInt();
                if (processId > 0) {
                    // 查询工序的计件单价
                    QSqlQuery query;
                    query.prepare("SELECT piece_rate FROM processes WHERE id = ?");
                    query.addBindValue(processId);
                    
                    double pieceRate = 0.0;
                    if (executeQuery(query, "查询工序计件单价失败", this) && query.next()) {
                        pieceRate = query.value(0).toDouble();
                    }
                    
                    // 查找该下拉框所在的行
                    int row = -1;
                    for (int i = 0; i < ui->tableWidget_productionEntry->rowCount(); i++) {
                        if (ui->tableWidget_productionEntry->cellWidget(i, 1) == processComboBox) {
                            row = i;
                            break;
                        }
                    }
                    
                    if (row >= 0) {
                        // 更新计件单价显示
                        QTableWidgetItem *priceItem = ui->tableWidget_productionEntry->item(row, 2);
                        if (priceItem) {
                            priceItem->setText(QString::number(pieceRate, 'f', 3));
                        }
                        
                        // 更新小计金额
                        QTableWidgetItem *quantityItem = ui->tableWidget_productionEntry->item(row, 3);
                        QTableWidgetItem *subtotalItem = ui->tableWidget_productionEntry->item(row, 4);
                        
                        if (quantityItem && subtotalItem) {
                            bool ok;
                            int quantity = quantityItem->text().toInt(&ok);
                            if (!ok) quantity = 1; // 默认数量为1
                            
                            double subtotal = quantity * pieceRate;
                            subtotalItem->setText(QString::number(subtotal, 'f', 3));
                            
                            // 更新总计
                            updateProductionTotal();
                        }
                    }
                }
            } else {
                // 更新计件单价和小计为0
                int row = -1;
                for (int i = 0; i < ui->tableWidget_productionEntry->rowCount(); i++) {
                    if (ui->tableWidget_productionEntry->cellWidget(i, 0) == toyComboBox) {
                        row = i;
                        break;
                    }
                }
                if (row >= 0) {
                    QTableWidgetItem *priceItem = ui->tableWidget_productionEntry->item(row, 2);
                    QTableWidgetItem *quantityItem = ui->tableWidget_productionEntry->item(row, 3);
                    QTableWidgetItem *subtotalItem = ui->tableWidget_productionEntry->item(row, 4);
                    
                    if (priceItem) priceItem->setText("0.000");
                    if (quantityItem) quantityItem->setText("1");
                    if (subtotalItem) subtotalItem->setText("0.000");
                }
            }
        });

        // 手动触发一次玩具选择变化事件来填充工序列表
        // 使用优化后的函数更新工序列表
        updateProcessListForToy(toyComboBox, processComboBox, toyId);

        // 设置当前工序选中项
        int processIndex = processComboBox->findData(processId);
        if (processIndex >= 0) {
            processComboBox->setCurrentIndex(processIndex);
        }

        // 设置计件单价
        QSqlQuery priceQuery;
        priceQuery.prepare("SELECT piece_rate FROM processes WHERE id = ?");
        priceQuery.addBindValue(processId);
        double pieceRate = 0.0;
        if (executeQuery(priceQuery, "查询工序计件单价失败", this) && priceQuery.next()) {
            pieceRate = priceQuery.value(0).toDouble();
        }

        QTableWidgetItem *priceItem = new QTableWidgetItem(QString::number(pieceRate, 'f', 3));
        priceItem->setFlags(priceItem->flags() & ~Qt::ItemIsEditable);
        priceItem->setTextAlignment(Qt::AlignCenter);
        priceItem->setBackground(QColor(240, 240, 240));
        priceItem->setFont(QFont("Arial", 18));  // 设置更大的字体
        ui->tableWidget_productionEntry->setItem(row, 2, priceItem);

        // 设置生产数量
        QTableWidgetItem *quantityItem = new QTableWidgetItem(QString::number(quantity));
        quantityItem->setFlags(quantityItem->flags() | Qt::ItemIsEditable);
        quantityItem->setTextAlignment(Qt::AlignCenter);
        quantityItem->setFont(QFont("Arial", 18));  // 设置更大的字体
        ui->tableWidget_productionEntry->setItem(row, 3, quantityItem);

        // 计算并设置小计金额
        double subtotal = quantity * pieceRate;
        QTableWidgetItem *subtotalItem = new QTableWidgetItem(QString::number(subtotal, 'f', 3));
        subtotalItem->setFlags(subtotalItem->flags() & ~Qt::ItemIsEditable);
        subtotalItem->setTextAlignment(Qt::AlignCenter);
        subtotalItem->setBackground(QColor(240, 240, 240));
        subtotalItem->setFont(QFont("Arial", 18));  // 设置更大的字体
        ui->tableWidget_productionEntry->setItem(row, 4, subtotalItem);

        // 连接工序选择变化信号，更新计件单价
        connect(processComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), [this, processComboBox](int index) {
            if (index < 0) return;
            
            // 获取工序ID
            int processId = processComboBox->currentData().toInt();
            if (processId <= 0) {
                return;
            }
            
            // 查找该下拉框所在的行
            int row = -1;
            for (int i = 0; i < ui->tableWidget_productionEntry->rowCount(); i++) {
                if (ui->tableWidget_productionEntry->cellWidget(i, 1) == processComboBox) {
                    row = i;
                    break;
                }
            }
            
            if (row < 0) {
                return;
            }
            
            // 查询工序的计件单价
            QSqlQuery query;
            query.prepare("SELECT piece_rate FROM processes WHERE id = ?");
            query.addBindValue(processId);
            
            double pieceRate = 0.0;
            if (executeQuery(query, "查询工序计件单价失败", this) && query.next()) {
                pieceRate = query.value(0).toDouble();
            }
            
            // 更新计件单价显示
            QTableWidgetItem *priceItem = ui->tableWidget_productionEntry->item(row, 2);
            if (priceItem) {
                priceItem->setText(QString::number(pieceRate, 'f', 3));
            }
            
            // 更新小计金额
            QTableWidgetItem *quantityItem = ui->tableWidget_productionEntry->item(row, 3);
            QTableWidgetItem *subtotalItem = ui->tableWidget_productionEntry->item(row, 4);
            
            if (quantityItem && subtotalItem) {
                bool ok;
                int quantity = quantityItem->text().toInt(&ok);
                if (!ok) quantity = 1; // 默认数量为1
                
                double subtotal = quantity * pieceRate;
                subtotalItem->setText(QString::number(subtotal, 'f', 3));
                
                // 更新总计
                updateProductionTotal();
            }
        });

        // 连接生产数量变化信号，更新小计金额
        connect(ui->tableWidget_productionEntry, &QTableWidget::cellChanged, [this](int row, int column) {
            if (column == 3) { // 数量列
                QTableWidgetItem *quantityItem = ui->tableWidget_productionEntry->item(row, 3);
                QTableWidgetItem *priceItem = ui->tableWidget_productionEntry->item(row, 2);
                QTableWidgetItem *subtotalItem = ui->tableWidget_productionEntry->item(row, 4);

                if (quantityItem && priceItem && subtotalItem) {
                    bool qtyOk, priceOk;
                    int quantity = quantityItem->text().toInt(&qtyOk);
                    double pieceRate = priceItem->text().toDouble(&priceOk);
                    
                    // 如果数量或单价无效，使用默认值
                    if (!qtyOk) quantity = 1;
                    if (!priceOk) pieceRate = 0.0;
                    
                    double subtotal = quantity * pieceRate;
                    subtotalItem->setText(QString::number(subtotal, 'f', 3));

                    updateProductionTotal();
                }
            }
        });

        // 创建删除按钮
        QPushButton *deleteButton = new QPushButton("删除");
        deleteButton->setStyleSheet("QPushButton { background-color: #e74c3c; color: white; border: none; padding: 8px 12px; border-radius: 4px; font-size: 16px; }");
        deleteButton->setMinimumHeight(40);  // 增加最小高度到40

        connect(deleteButton, &QPushButton::clicked, [this, row]() {
            if (QMessageBox::question(this, "确认删除", "确定要删除这条生产记录吗？",
                                      QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {

                QComboBox *toyComboBox = qobject_cast<QComboBox*>(ui->tableWidget_productionEntry->cellWidget(row, 0));
                QComboBox *processComboBox = qobject_cast<QComboBox*>(ui->tableWidget_productionEntry->cellWidget(row, 1));

                if (toyComboBox && processComboBox) {
                    int empId = ui->comboBox_entryEmployee->currentData().toInt();
                    int toyIdVal = toyComboBox->currentData().toInt();
                    int processIdVal = processComboBox->currentData().toInt();
                    QString date = QDate::currentDate().toString("yyyy-MM-dd");

                    // 从数据库删除记录（新版本表）
                    QSqlQuery deleteQuery;
                    deleteQuery.prepare("DELETE FROM production_v2 WHERE date = ? AND employee_id = ? AND toy_id = ? AND process_id = ?");
                    deleteQuery.addBindValue(date);
                    deleteQuery.addBindValue(empId);
                    deleteQuery.addBindValue(toyIdVal);
                    deleteQuery.addBindValue(processIdVal);

                    if (executeQuery(deleteQuery, "删除生产记录失败", this)) {
                        ui->tableWidget_productionEntry->removeRow(row);
                        updateProductionTotal();
                        QMessageBox::information(this, "成功", "生产记录删除成功");
                        updateDashboard();
                    }
                }
            }
        });
        ui->tableWidget_productionEntry->setCellWidget(row, 5, deleteButton);
    }

    // 如果没有数据，添加一个空行
    if (ui->tableWidget_productionEntry->rowCount() == 0) {
        onAddProductionRow();
    }

    // 更新总计
    updateProductionTotal();

    // 刷新表格显示
    ui->tableWidget_productionEntry->viewport()->update();
    ui->tableWidget_productionEntry->repaint();
}

// 删除玩具
void MainWindow::onDeleteToy()
{
    int currentRow = ui->tableWidget_products->currentRow();
    if (currentRow < 0) {
        QMessageBox::warning(this, "警告", "请先选择要删除的玩具");
        return;
    }
    QString toyId = ui->tableWidget_products->item(currentRow, 0)->text();
    QString name = ui->tableWidget_products->item(currentRow, 1)->text();

    if (QMessageBox::question(this, "确认删除", "确定要删除玩具 " + name + " 吗？") == QMessageBox::Yes) {
        QSqlQuery query;
        query.prepare("DELETE FROM toys WHERE toy_id = ?");
        query.addBindValue(toyId);

        if (query.exec()) {
            QMessageBox::information(this, "成功", "玩具删除成功");
            loadToysWithPagination(currentToyPage);  // 使用分页加载
            updateDashboard();
        } else {
            QMessageBox::critical(this, "错误", "玩具删除失败: " + query.lastError().text());
        }
    }
}

// 添加生产记录行 - 升级版本（支持产品+工序维度）
void MainWindow::onAddProductionRow()
{
    int row = ui->tableWidget_productionEntry->rowCount();
    ui->tableWidget_productionEntry->insertRow(row);

    // 设置新行的行高
    ui->tableWidget_productionEntry->setRowHeight(row, 60);  // 增加行高到60

    // 第1列：玩具产品下拉框
    QComboBox *toyComboBox = new QComboBox();
    toyComboBox->setObjectName(QString("toyComboBox_%1").arg(row));
    toyComboBox->setMinimumHeight(40);  // 增加最小高度到40
    toyComboBox->setStyleSheet("QComboBox { font-size: 16px; min-height: 40px; }"
                               "QComboBox QAbstractItemView { font-size: 18px; min-height: 30px; }");  // 设置更大的字体

    // 使用优化后的函数加载玩具数据
    loadToyDataIntoComboBox(toyComboBox);

    if (toyComboBox->count() <= 1) {  // 只有默认选项
        QMessageBox::warning(this, "提示", "没有可用的玩具产品，请先添加玩具产品");
        ui->tableWidget_productionEntry->removeRow(row);
        return;
    }

    ui->tableWidget_productionEntry->setCellWidget(row, 0, toyComboBox);

    // 第2列：工序下拉框
    QComboBox *processComboBox = new QComboBox();
    processComboBox->setObjectName(QString("processComboBox_%1").arg(row));
    processComboBox->setMinimumHeight(40);  // 增加最小高度到40
    processComboBox->setStyleSheet("QComboBox { font-size: 16px; min-height: 40px; }"
                                   "QComboBox QAbstractItemView { font-size: 18px; min-height: 30px; }");  // 设置更大的字体
    processComboBox->addItem("请先选择玩具产品", -1);
    ui->tableWidget_productionEntry->setCellWidget(row, 1, processComboBox);

    // 第3列：计件单价（根据工序自动填充）
    QTableWidgetItem *priceItem = new QTableWidgetItem("0.000");
    priceItem->setFlags(priceItem->flags() & ~Qt::ItemIsEditable);
    priceItem->setTextAlignment(Qt::AlignCenter);
    priceItem->setBackground(QColor(240, 240, 240));
    priceItem->setFont(QFont("Arial", 18));  // 设置更大的字体
    ui->tableWidget_productionEntry->setItem(row, 2, priceItem);

    // 第4列：生产数量
    QTableWidgetItem *quantityItem = new QTableWidgetItem("1");
    quantityItem->setFlags(quantityItem->flags() | Qt::ItemIsEditable);
    quantityItem->setTextAlignment(Qt::AlignCenter);
    quantityItem->setFont(QFont("Arial", 18));  // 设置更大的字体
    ui->tableWidget_productionEntry->setItem(row, 3, quantityItem);

    // 第5列：小计金额
    QTableWidgetItem *subtotalItem = new QTableWidgetItem("0.000");
    subtotalItem->setFlags(subtotalItem->flags() & ~Qt::ItemIsEditable);
    subtotalItem->setTextAlignment(Qt::AlignCenter);
    subtotalItem->setBackground(QColor(240, 240, 240));
    subtotalItem->setFont(QFont("Arial", 18));  // 设置更大的字体
    ui->tableWidget_productionEntry->setItem(row, 4, subtotalItem);

    // 第6列：删除按钮
    QPushButton *deleteButton = new QPushButton("删除");
    deleteButton->setStyleSheet("QPushButton { background-color: #e74c3c; color: white; border: none; padding: 8px 12px; border-radius: 4px; font-size: 16px; }");
    deleteButton->setMinimumHeight(40);  // 增加最小高度到40

    connect(deleteButton, &QPushButton::clicked, [this, deleteButton]() {
        int currentRow = -1;
        for (int i = 0; i < ui->tableWidget_productionEntry->rowCount(); i++) {
            if (ui->tableWidget_productionEntry->cellWidget(i, 5) == deleteButton) {
                currentRow = i;
                break;
            }
        }
        if (currentRow >= 0) {
            if (QMessageBox::question(this, "确认删除", "确定要删除这条生产记录吗？",
                                      QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {

                QComboBox *toyComboBox = qobject_cast<QComboBox*>(ui->tableWidget_productionEntry->cellWidget(currentRow, 0));
                QComboBox *processComboBox = qobject_cast<QComboBox*>(ui->tableWidget_productionEntry->cellWidget(currentRow, 1));
                if (toyComboBox && processComboBox) {
                    int employeeId = ui->comboBox_entryEmployee->currentData().toInt();
                    int toyId = toyComboBox->currentData().toInt();
                    int processId = processComboBox->currentData().toInt();
                    QString date = ui->dateEdit_entryDate->date().toString("yyyy-MM-dd");

                    // 从数据库删除记录（新版本表）
                    QSqlQuery deleteQuery;
                    deleteQuery.prepare("DELETE FROM production_v2 WHERE date = ? AND employee_id = ? AND toy_id = ? AND process_id = ?");
                    deleteQuery.addBindValue(date);
                    deleteQuery.addBindValue(employeeId);
                    deleteQuery.addBindValue(toyId);
                    deleteQuery.addBindValue(processId);

                    if (executeQuery(deleteQuery, "删除生产记录失败", this)) {
                        ui->tableWidget_productionEntry->removeRow(currentRow);
                        updateProductionTotal();
                        QMessageBox::information(this, "成功", "生产记录删除成功");
                        updateDashboard();
                    }
                } else {
                    // 如果没有玩具下拉框（可能是新添加的空行），直接删除界面行
                    ui->tableWidget_productionEntry->removeRow(currentRow);
                    updateProductionTotal();
                }
            }
        }
    });
    ui->tableWidget_productionEntry->setCellWidget(row, 5, deleteButton);

    // 连接玩具选择变化信号，更新工序列表
    connect(toyComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), [this, toyComboBox, processComboBox](int index) {
        if (index < 0) return;

        int toyId = toyComboBox->currentData().toInt();
        
        // 使用优化后的函数更新工序列表
        updateProcessListForToy(toyComboBox, processComboBox, toyId);
        
        // 如果工序列表不为空，自动选择第一个工序（除了提示项）
        if (processComboBox->count() > 1) {
            processComboBox->setCurrentIndex(1);
            
            // 直接更新计件单价，而不是通过信号触发
            int processId = processComboBox->currentData().toInt();
            if (processId > 0) {
                // 查询工序的计件单价
                QSqlQuery query;
                query.prepare("SELECT piece_rate FROM processes WHERE id = ?");
                query.addBindValue(processId);
                
                double pieceRate = 0.0;
                if (executeQuery(query, "查询工序计件单价失败", this) && query.next()) {
                    pieceRate = query.value(0).toDouble();
                }
                
                // 查找该下拉框所在的行
                int row = -1;
                for (int i = 0; i < ui->tableWidget_productionEntry->rowCount(); i++) {
                    if (ui->tableWidget_productionEntry->cellWidget(i, 1) == processComboBox) {
                        row = i;
                        break;
                    }
                }
                
                if (row >= 0) {
                    // 更新计件单价显示
                    QTableWidgetItem *priceItem = ui->tableWidget_productionEntry->item(row, 2);
                    if (priceItem) {
                        priceItem->setText(QString::number(pieceRate, 'f', 3));
                    }
                    
                    // 更新小计金额
                    QTableWidgetItem *quantityItem = ui->tableWidget_productionEntry->item(row, 3);
                    QTableWidgetItem *subtotalItem = ui->tableWidget_productionEntry->item(row, 4);
                    
                    if (quantityItem && subtotalItem) {
                        bool ok;
                        int quantity = quantityItem->text().toInt(&ok);
                        if (!ok) quantity = 1; // 默认数量为1
                        
                        double subtotal = quantity * pieceRate;
                        subtotalItem->setText(QString::number(subtotal, 'f', 3));
                        
                        // 更新总计
                        updateProductionTotal();
                    }
                }
            }
        } else {
            // 更新计件单价和小计为0
            int row = -1;
            for (int i = 0; i < ui->tableWidget_productionEntry->rowCount(); i++) {
                if (ui->tableWidget_productionEntry->cellWidget(i, 0) == toyComboBox) {
                    row = i;
                    break;
                }
            }
            if (row >= 0) {
                QTableWidgetItem *priceItem = ui->tableWidget_productionEntry->item(row, 2);
                QTableWidgetItem *quantityItem = ui->tableWidget_productionEntry->item(row, 3);
                QTableWidgetItem *subtotalItem = ui->tableWidget_productionEntry->item(row, 4);
                
                if (priceItem) priceItem->setText("0.000");
                if (quantityItem) quantityItem->setText("1");
                if (subtotalItem) subtotalItem->setText("0.000");
            }
        }
    });

    // 连接工序选择变化信号，更新计件单价
    connect(processComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), [this, processComboBox](int index) {
        if (index < 0) return;
        
        // 获取工序ID
        int processId = processComboBox->currentData().toInt();
        if (processId <= 0) {
            return;
        }
        
        // 查找该下拉框所在的行
        int row = -1;
        for (int i = 0; i < ui->tableWidget_productionEntry->rowCount(); i++) {
            if (ui->tableWidget_productionEntry->cellWidget(i, 1) == processComboBox) {
                row = i;
                break;
            }
        }
        
        if (row < 0) {
            return;
        }
        
        // 查询工序的计件单价
        QSqlQuery query;
        query.prepare("SELECT piece_rate FROM processes WHERE id = ?");
        query.addBindValue(processId);
        
        double pieceRate = 0.0;
        if (executeQuery(query, "查询工序计件单价失败", this) && query.next()) {
            pieceRate = query.value(0).toDouble();
        }
        
        // 更新计件单价显示
        QTableWidgetItem *priceItem = ui->tableWidget_productionEntry->item(row, 2);
        if (priceItem) {
            priceItem->setText(QString::number(pieceRate, 'f', 3));
        }
        
        // 更新小计金额
        QTableWidgetItem *quantityItem = ui->tableWidget_productionEntry->item(row, 3);
        QTableWidgetItem *subtotalItem = ui->tableWidget_productionEntry->item(row, 4);
        
        if (quantityItem && subtotalItem) {
            bool ok;
            int quantity = quantityItem->text().toInt(&ok);
            if (!ok) quantity = 1; // 默认数量为1
            
            double subtotal = quantity * pieceRate;
            subtotalItem->setText(QString::number(subtotal, 'f', 3));
            
            // 更新总计
            updateProductionTotal();
        }
    });

    // 连接生产数量变化信号，更新小计金额
    connect(ui->tableWidget_productionEntry, &QTableWidget::cellChanged, [this](int row, int column) {
        if (column == 3) { // 数量列
            QTableWidgetItem *quantityItem = ui->tableWidget_productionEntry->item(row, 3);
            QTableWidgetItem *priceItem = ui->tableWidget_productionEntry->item(row, 2);
            QTableWidgetItem *subtotalItem = ui->tableWidget_productionEntry->item(row, 4);

            if (quantityItem && priceItem && subtotalItem) {
                bool qtyOk, priceOk;
                int quantity = quantityItem->text().toInt(&qtyOk);
                double pieceRate = priceItem->text().toDouble(&priceOk);
                
                // 如果数量或单价无效，使用默认值
                if (!qtyOk) quantity = 1;
                if (!priceOk) pieceRate = 0.0;
                
                double subtotal = quantity * pieceRate;
                subtotalItem->setText(QString::number(subtotal, 'f', 3));

                updateProductionTotal();
            }
        }
    });

    // 设置行号属性
    toyComboBox->setProperty("row", row);
    processComboBox->setProperty("row", row);
}

// 删除生产记录行
void MainWindow::onRemoveProductionRow()
{
    int currentRow = ui->tableWidget_productionEntry->currentRow();
    if (currentRow < 0) {
        QMessageBox::information(this, "提示", "请先选择要删除的行");
        return;
    }

    if (QMessageBox::question(this, "确认删除", "确定要删除选中的生产记录吗？",
                              QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {

        // 获取要删除记录的关键信息
        QComboBox *toyComboBox = qobject_cast<QComboBox*>(ui->tableWidget_productionEntry->cellWidget(currentRow, 0));
        QComboBox *processComboBox = qobject_cast<QComboBox*>(ui->tableWidget_productionEntry->cellWidget(currentRow, 1));

        if (toyComboBox && processComboBox) {
            int employeeId = ui->comboBox_entryEmployee->currentData().toInt();
            int toyId = toyComboBox->currentData().toInt();
            int processId = processComboBox->currentData().toInt();
            QString date = ui->dateEdit_entryDate->date().toString("yyyy-MM-dd");

            // 从数据库删除记录（使用新版本表，包含工序ID）
            QSqlQuery deleteQuery;
            deleteQuery.prepare("DELETE FROM production_v2 WHERE date = ? AND employee_id = ? AND toy_id = ? AND process_id = ?");
            deleteQuery.addBindValue(date);
            deleteQuery.addBindValue(employeeId);
            deleteQuery.addBindValue(toyId);
            deleteQuery.addBindValue(processId);

            if (executeQuery(deleteQuery, "删除生产记录失败", this)) {
                // 数据库删除成功，删除界面行
                ui->tableWidget_productionEntry->removeRow(currentRow);
                updateProductionTotal();
                QMessageBox::information(this, "成功", "生产记录删除成功");
                updateDashboard(); // 更新仪表盘数据
            }
        } else {
            // 如果没有玩具下拉框（可能是新添加的空行），直接删除界面行
            ui->tableWidget_productionEntry->removeRow(currentRow);
            updateProductionTotal();
        }
    }
}

// 保存生产记录
void MainWindow::onSaveProduction()
{
    int employeeId = ui->comboBox_entryEmployee->currentData().toInt();
    QString date = ui->dateEdit_entryDate->date().toString("yyyy-MM-dd");

    // 数据验证
    if (employeeId <= 0) {
        QMessageBox::warning(this, "数据验证失败", "请先选择员工");
        return;
    }

    // 验证是否有有效的生产记录行
    bool hasValidData = false;
    for (int row = 0; row < ui->tableWidget_productionEntry->rowCount(); row++) {
        QComboBox *toyComboBox = qobject_cast<QComboBox*>(ui->tableWidget_productionEntry->cellWidget(row, 0));
        QComboBox *processComboBox = qobject_cast<QComboBox*>(ui->tableWidget_productionEntry->cellWidget(row, 1));
        QTableWidgetItem *quantityItem = ui->tableWidget_productionEntry->item(row, 3);
        if (toyComboBox && processComboBox && quantityItem && !quantityItem->text().isEmpty()) {
            bool ok;
            int quantity = quantityItem->text().toInt(&ok);
            if (ok && quantity > 0) {
                hasValidData = true;
                break;
            }
        }
    }

    if (!hasValidData) {
        QMessageBox::warning(this, "数据验证失败", "请至少添加一条有效的生产记录（数量大于0）");
        return;
    }

    // 开始事务
    if (!beginTransaction(db, "保存生产记录时开启事务失败", this)) {
        return;
    }

    int savedRecords = 0;

    // 遍历所有行保存数据
    for (int row = 0; row < ui->tableWidget_productionEntry->rowCount(); row++) {
        QComboBox *toyComboBox = qobject_cast<QComboBox*>(ui->tableWidget_productionEntry->cellWidget(row, 0));
        QComboBox *processComboBox = qobject_cast<QComboBox*>(ui->tableWidget_productionEntry->cellWidget(row, 1));
        if (!toyComboBox || !processComboBox) {
            continue; // 跳过无效行而不是回滚整个事务
        }

        int toyId = toyComboBox->currentData().toInt();
        int processId = processComboBox->currentData().toInt();
        QTableWidgetItem *quantityItem = ui->tableWidget_productionEntry->item(row, 3);
        if (!quantityItem || quantityItem->text().isEmpty()) {
            continue; // 跳过空数量行
        }

        QString quantityStr = quantityItem->text().trimmed();
        bool ok;
        int quantity = quantityStr.toInt(&ok);

        if (!ok || quantity <= 0) {
            QMessageBox::warning(this, "数据验证失败",
                QString("第%1行数量'%2'无效，请输入大于0的整数")
                .arg(row + 1).arg(quantityStr));
            db.rollback();
            return;
        }

        if (toyId <= 0) {
            QMessageBox::warning(this, "数据验证失败",
                QString("第%1行请选择有效的玩具类型").arg(row + 1));
            db.rollback();
            return;
        }

        if (processId <= 0) {
            QMessageBox::warning(this, "数据验证失败",
                QString("第%1行请选择有效的工序").arg(row + 1));
            db.rollback();
            return;
        }

        // 获取工序的计件单价
        QSqlQuery priceQuery;
        priceQuery.prepare("SELECT piece_rate FROM processes WHERE id = ?");
        priceQuery.addBindValue(processId);
        double pieceRate = 0.0;
        if (executeQuery(priceQuery, "查询工序计件单价失败", this) && priceQuery.next()) {
            pieceRate = priceQuery.value(0).toDouble();
        }

        // 计算小计金额
        double subtotal = quantity * pieceRate;

        // 检查是否存在重复记录
        QSqlQuery checkQuery;
        checkQuery.prepare("SELECT COUNT(*) FROM production_v2 WHERE date = ? AND employee_id = ? AND toy_id = ? AND process_id = ?");
        checkQuery.addBindValue(date);
        checkQuery.addBindValue(employeeId);
        checkQuery.addBindValue(toyId);
        checkQuery.addBindValue(processId);

        if (!executeQuery(checkQuery, "检查生产记录是否存在时失败", this)) {
            db.rollback();
            return;
        }

        if (checkQuery.next() && checkQuery.value(0).toInt() > 0) {
            // 存在重复记录，询问是否覆盖
            int reply = QMessageBox::question(this, "记录已存在",
                QString("员工'%1'在%2已有'%3-%4'的生产记录，是否更新数量？")
                .arg(ui->comboBox_entryEmployee->currentText())
                .arg(date)
                .arg(toyComboBox->currentText())
                .arg(processComboBox->currentText()),
                QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);

            if (reply == QMessageBox::Cancel) {
                db.rollback();
                return;
            } else if (reply == QMessageBox::Yes) {
                // 更新记录
                QSqlQuery updateQuery;
                updateQuery.prepare("UPDATE production_v2 SET quantity = ?, piece_rate = ?, subtotal = ? WHERE date = ? AND employee_id = ? AND toy_id = ? AND process_id = ?");
                updateQuery.addBindValue(quantity);
                updateQuery.addBindValue(pieceRate);
                updateQuery.addBindValue(subtotal);
                updateQuery.addBindValue(date);
                updateQuery.addBindValue(employeeId);
                updateQuery.addBindValue(toyId);
                updateQuery.addBindValue(processId);
                if (!executeQuery(updateQuery, QString("更新第%1行生产记录失败").arg(row + 1), this)) {
                    db.rollback();
                    return;
                }
                savedRecords++;
            }
            // No的情况跳过该行
        } else {
            // 插入新记录
            QSqlQuery insertQuery;
            insertQuery.prepare("INSERT INTO production_v2 (date, employee_id, toy_id, process_id, quantity, piece_rate, subtotal) VALUES (?, ?, ?, ?, ?, ?, ?)");
            insertQuery.addBindValue(date);
            insertQuery.addBindValue(employeeId);
            insertQuery.addBindValue(toyId);
            insertQuery.addBindValue(processId);
            insertQuery.addBindValue(quantity);
            insertQuery.addBindValue(pieceRate);
            insertQuery.addBindValue(subtotal);
            if (!executeQuery(insertQuery, QString("保存第%1行生产记录失败").arg(row + 1), this)) {
                db.rollback();
                return;
            }
            savedRecords++;
        }
    }

    // 提交事务
    if (!db.commit()) {
        db.rollback();
        QMessageBox::critical(this, "事务错误", "保存生产记录时提交事务失败：" + db.lastError().text());
        return;
    }

    // 操作成功
    if (savedRecords > 0) {
        QMessageBox::information(this, "保存成功",
            QString("成功保存%1条生产记录\n日期：%2\n员工：%3")
            .arg(savedRecords)
            .arg(date)
            .arg(ui->comboBox_entryEmployee->currentText()));
        updateDashboard();

        // �空空表格，保留一行用于下次录入
        ui->tableWidget_productionEntry->setRowCount(0);
        onAddProductionRow(); // 添加一行新的空行
    } else {
        QMessageBox::information(this, "提示", "没有保存任何记录，请检查数据后重试");
    }
}

// 生成员工日报表 - 升级版本（支持工序维度和分页）
void MainWindow::onGenerateDailyReport()
{
    // 添加调试信息
    qDebug() << "开始执行员工日报表查询";
    
    int employeeId = ui->comboBox_dailyReportEmployee->currentData().toInt();
    QString startDate = ui->dateEdit_startDate->date().toString("yyyy-MM-dd");
    QString endDate = ui->dateEdit_endDate->date().toString("yyyy-MM-dd");

    qDebug() << "查询参数: employeeId=" << employeeId << ", startDate=" << startDate << ", endDate=" << endDate;

    // 数据验证
    if (employeeId <= 0) {
        QMessageBox::warning(this, "数据验证失败", "请先选择员工");
        return;
    }

    if (startDate > endDate) {
        QMessageBox::warning(this, "数据验证失败", "开始日期不能晚于结束日期");
        return;
    }

    // 清空表格
    if (!ui->tableWidget_dailyReport) {
        qDebug() << "错误：tableWidget_dailyReport 为空指针";
        QMessageBox::critical(this, "错误", "界面组件未正确初始化");
        return;
    }
    ui->tableWidget_dailyReport->setRowCount(0);

    // 查询日报表数据总数 - 支持工序维度
    QSqlQuery countQuery;
    countQuery.prepare("SELECT COUNT(*) FROM production_v2 pv2 "
                      "JOIN toys t ON pv2.toy_id = t.id "
                      "JOIN processes p ON pv2.process_id = p.id "
                      "WHERE pv2.employee_id = ? AND pv2.date BETWEEN ? AND ?");
    countQuery.addBindValue(employeeId);
    countQuery.addBindValue(startDate);
    countQuery.addBindValue(endDate);

    if (!executeQuery(countQuery, "查询日报表数据总数失败", this)) {
        return;
    }

    int totalRecords = 0;
    if (countQuery.next()) {
        totalRecords = countQuery.value(0).toInt();
    }
    totalDailyReportRecords = totalRecords;
    
    qDebug() << "总记录数: " << totalRecords;

    // 计算总页数
    int totalPages = (totalRecords + itemsPerPage - 1) / itemsPerPage;
    if (totalPages == 0) totalPages = 1;
    
    qDebug() << "总页数: " << totalPages << ", 当前页: " << currentDailyReportPage;

    // 检查当前页码是否超出范围
    if (currentDailyReportPage >= totalPages && totalPages > 0) {
        currentDailyReportPage = totalPages - 1;
    }

    // 计算偏移量
    int offset = currentDailyReportPage * itemsPerPage;
    
    qDebug() << "偏移量: " << offset << ", 每页记录数: " << itemsPerPage;

    // 查询日报表数据 - 支持工序维度和分页
    QSqlQuery query;
    query.prepare("SELECT pv2.date, t.name as toy_name, p.name as process_name, "
                  "pv2.quantity, pv2.piece_rate, pv2.subtotal "
                  "FROM production_v2 pv2 "
                  "JOIN toys t ON pv2.toy_id = t.id "
                  "JOIN processes p ON pv2.process_id = p.id "
                  "WHERE pv2.employee_id = ? AND pv2.date BETWEEN ? AND ? "
                  "ORDER BY pv2.date, t.name, p.name "
                  "LIMIT ? OFFSET ?");
    query.addBindValue(employeeId);
    query.addBindValue(startDate);
    query.addBindValue(endDate);
    query.addBindValue(itemsPerPage);
    query.addBindValue(offset);

    if (!executeQuery(query, "查询日报表数据失败", this)) {
        return;
    }

    // 按日期分组计算每日总收入
    QMap<QString, double> dailyTotalMap;
    QList<QStringList> reportData;
    double grandTotal = 0.0;
    int totalQuantity = 0;

    while (query.next()) {
        QString date = query.value(0).toString();
        QString toyName = query.value(1).toString();
        QString processName = query.value(2).toString();
        int quantity = query.value(3).toInt();
        double pieceRate = query.value(4).toDouble();
        double subtotal = query.value(5).toDouble();

        QStringList rowData;
        rowData << date << toyName << processName << QString::number(quantity)
                << QString::number(pieceRate, 'f', 3)
                << QString::number(subtotal, 'f', 3);
        reportData << rowData;

        // 统计数据
        dailyTotalMap[date] += subtotal;
        grandTotal += subtotal;
        totalQuantity += quantity;
    }
    
    qDebug() << "查询到的记录数: " << reportData.size();

    // 处理空结果
    if (reportData.isEmpty()) {
        QMessageBox::information(this, "提示", "在所选日期范围内没有找到生产记录");
        statusBar()->showMessage("在所选日期范围内没有找到生产记录，总收入：¥0.00");
        // 更新分页控件状态
        updatePaginationControls("dailyReport", currentDailyReportPage, totalPages);
        return;
    }

    // 填充表格 - 添加更详细的异常处理和检查
    try {
        QString currentDate = "";
        for (int i = 0; i < reportData.size(); i++) {
            const QStringList &rowData = reportData[i];
            
            // 检查 rowData 是否有效
            if (rowData.size() < 6) {
                qDebug() << "警告：rowData 数据不完整，跳过第" << i << "行";
                continue;
            }
            
            // 检查表格指针
            if (!ui->tableWidget_dailyReport) {
                qDebug() << "错误：tableWidget_dailyReport 在填充过程中变为 null";
                QMessageBox::critical(this, "错误", "界面组件在填充过程中出现问题");
                return;
            }
            
            int row = ui->tableWidget_dailyReport->rowCount();
            qDebug() << "准备插入第" << row << "行";
            
            // 插入新行并检查是否成功
            ui->tableWidget_dailyReport->insertRow(row);
            if (ui->tableWidget_dailyReport->rowCount() <= row) {
                qDebug() << "错误：插入新行失败";
                continue;
            }
            
            // 填充数据 - 新表格结构：日期、玩具名称、工序名称、数量、单价、小计金额、当日总收入
            for (int col = 0; col < 6 && col < rowData.size(); col++) {
                // 添加组件有效性检查
                if (!ui->tableWidget_dailyReport) {
                    qDebug() << "错误：tableWidget_dailyReport 在填充数据时变为 null";
                    QMessageBox::critical(this, "错误", "界面组件在填充数据时出现问题");
                    return;
                }
                
                // 检查行和列索引
                if (row >= ui->tableWidget_dailyReport->rowCount() || col >= ui->tableWidget_dailyReport->columnCount()) {
                    qDebug() << "警告：行或列索引越界，row=" << row << ", col=" << col;
                    continue;
                }
                
                // 创建并设置表格项
                QTableWidgetItem *item = new QTableWidgetItem(rowData[col]);
                if (item) {
                    item->setTextAlignment(Qt::AlignCenter);
                    ui->tableWidget_dailyReport->setItem(row, col, item);
                } else {
                    qDebug() << "错误：无法创建 QTableWidgetItem";
                }
            }

            // 处理当日总收入列（第7列）
            QString itemDate = rowData[0];
            if (currentDate != itemDate) {
                currentDate = itemDate;
            }

            // 检查是否是该日期的最后一条记录
            bool isLastRecordOfDay = (i == reportData.size() - 1) ||
                                     (i < reportData.size() - 1 && reportData[i+1][0] != itemDate);

            // 添加组件有效性检查
            if (!ui->tableWidget_dailyReport) {
                qDebug() << "错误：tableWidget_dailyReport 在设置总收入时变为 null";
                QMessageBox::critical(this, "错误", "界面组件在设置总收入时出现问题");
                return;
            }
            
            // 检查行索引
            if (row >= ui->tableWidget_dailyReport->rowCount()) {
                qDebug() << "警告：行索引越界，row=" << row;
                continue;
            }

            if (isLastRecordOfDay) {
                // 在最后一列显示当日总收入
                QTableWidgetItem *dailyTotalItem = new QTableWidgetItem(QString::number(dailyTotalMap[itemDate], 'f', 3));
                if (dailyTotalItem) {
                    dailyTotalItem->setTextAlignment(Qt::AlignCenter);
                    dailyTotalItem->setBackground(QColor(230, 230, 230));
                    dailyTotalItem->setFont(QFont("", -1, QFont::Bold));
                    ui->tableWidget_dailyReport->setItem(row, 6, dailyTotalItem);
                } else {
                    qDebug() << "错误：无法创建当日总收入项";
                }
            } else {
                QTableWidgetItem *emptyItem = new QTableWidgetItem("");
                if (emptyItem) {
                    emptyItem->setTextAlignment(Qt::AlignCenter);
                    ui->tableWidget_dailyReport->setItem(row, 6, emptyItem);
                }
            }
        }
        qDebug() << "表格数据填充完成";
    } catch (const std::exception& e) {
        qDebug() << "填充表格数据时发生异常: " << e.what();
        QMessageBox::critical(this, "错误", "填充表格数据时发生异常: " + QString(e.what()));
        return;
    } catch (...) {
        qDebug() << "填充表格数据时发生未知异常";
        QMessageBox::critical(this, "错误", "填充表格数据时发生未知异常");
        return;
    }

    // 更新状态栏显示 - 添加异常处理
    try {
        qDebug() << "准备更新状态栏显示";
        QString statusMessage = QString("日期范围：%1 至 %2，总数量：%3 件，总收入：¥%4")
                             .arg(startDate).arg(endDate)
                             .arg(totalQuantity)
                             .arg(QString::number(grandTotal, 'f', 3));
        qDebug() << "状态栏消息: " << statusMessage;
        if (statusBar()) {
            statusBar()->showMessage(statusMessage);
            qDebug() << "状态栏更新完成";
        } else {
            qDebug() << "警告：statusBar 为空指针";
        }
    } catch (const std::exception& e) {
        qDebug() << "更新状态栏时发生异常: " << e.what();
    } catch (...) {
        qDebug() << "更新状态栏时发生未知异常";
    }

    // 更新分页控件状态 - 添加异常处理
    try {
        qDebug() << "准备更新分页控件状态";
        updatePaginationControls("dailyReport", currentDailyReportPage, totalPages);
        qDebug() << "分页控件状态更新完成";
    } catch (const std::exception& e) {
        qDebug() << "更新分页控件时发生异常: " << e.what();
    } catch (...) {
        qDebug() << "更新分页控件时发生未知异常";
    }
    
    qDebug() << "员工日报表查询完成";
}

// 生成员工月报表 - 升级版本（支持工序维度和分页）
void MainWindow::onGenerateMonthlyReport()
{
    int employeeId = ui->comboBox_monthlyReportEmployee->currentData().toInt();
    QString month = ui->dateEdit_month->date().toString("yyyy-MM");
    QString monthStart = month + "-01";
    QString monthEnd = QDate::fromString(month + "-01", "yyyy-MM-dd").addMonths(1).addDays(-1).toString("yyyy-MM-dd");

    // 数据验证
    if (employeeId <= 0) {
        QMessageBox::warning(this, "数据验证失败", "请先选择员工");
        return;
    }

    // 清空表格
    ui->tableWidget_monthlyReport->setRowCount(0);

    // 查询月报表数据总数 - 支持工序维度
    QSqlQuery countQuery;
    countQuery.prepare("SELECT COUNT(*) FROM ("
                      "SELECT t.name as toy_name, p.name as process_name "
                      "FROM production_v2 pv2 "
                      "JOIN toys t ON pv2.toy_id = t.id "
                      "JOIN processes p ON pv2.process_id = p.id "
                      "WHERE pv2.employee_id = ? AND pv2.date BETWEEN ? AND ? "
                      "GROUP BY t.name, p.name, pv2.piece_rate) AS grouped_data");
    countQuery.addBindValue(employeeId);
    countQuery.addBindValue(monthStart);
    countQuery.addBindValue(monthEnd);

    if (!executeQuery(countQuery, "查询月报表数据总数失败", this)) {
        return;
    }

    int totalRecords = 0;
    if (countQuery.next()) {
        totalRecords = countQuery.value(0).toInt();
    }
    totalMonthlyReportRecords = totalRecords;

    // 计算总页数
    int totalPages = (totalRecords + itemsPerPage - 1) / itemsPerPage;
    if (totalPages == 0) totalPages = 1;

    // 检查当前页码是否超出范围
    if (currentMonthlyReportPage >= totalPages && totalPages > 0) {
        currentMonthlyReportPage = totalPages - 1;
    }

    // 计算偏移量
    int offset = currentMonthlyReportPage * itemsPerPage;

    // 查询月报表数据 - 支持工序维度和分页
    QSqlQuery query;
    query.prepare("SELECT t.name as toy_name, p.name as process_name, "
                  "SUM(pv2.quantity) as total_qty, pv2.piece_rate, "
                  "SUM(pv2.subtotal) as total_amount "
                  "FROM production_v2 pv2 "
                  "JOIN toys t ON pv2.toy_id = t.id "
                  "JOIN processes p ON pv2.process_id = p.id "
                  "WHERE pv2.employee_id = ? AND pv2.date BETWEEN ? AND ? "
                  "GROUP BY t.name, p.name, pv2.piece_rate "
                  "ORDER BY t.name, p.name "
                  "LIMIT ? OFFSET ?");
    query.addBindValue(employeeId);
    query.addBindValue(monthStart);
    query.addBindValue(monthEnd);
    query.addBindValue(itemsPerPage);
    query.addBindValue(offset);

    if (!executeQuery(query, "查询月报表数据失败", this)) {
        return;
    }

    // 计算月总收入
    double monthlyTotal = 0;
    int row = 0;
    bool hasData = false;

    while (query.next()) {
        hasData = true;
        ui->tableWidget_monthlyReport->insertRow(row);
        ui->tableWidget_monthlyReport->setItem(row, 0, new QTableWidgetItem(query.value(0).toString())); // 玩具名称
        ui->tableWidget_monthlyReport->setItem(row, 1, new QTableWidgetItem(query.value(1).toString())); // 工序名称
        ui->tableWidget_monthlyReport->setItem(row, 2, new QTableWidgetItem(QString::number(query.value(2).toInt()))); // 总数量
        ui->tableWidget_monthlyReport->setItem(row, 3, new QTableWidgetItem(QString::number(query.value(3).toDouble(), 'f', 3))); // 单价
        ui->tableWidget_monthlyReport->setItem(row, 4, new QTableWidgetItem(QString::number(query.value(4).toDouble(), 'f', 3))); // 计件收入

        monthlyTotal += query.value(4).toDouble();
        row++;
    }

    // 处理空结果
    if (!hasData) {
        QMessageBox::information(this, "提示", QString("在 %1 月份没有找到生产记录").arg(month));
        statusBar()->showMessage(QString("%1月份无生产记录，总收入：¥0.00").arg(month));
        // 更新分页控件状态
        updatePaginationControls("monthlyReport", currentMonthlyReportPage, totalPages);
        return;
    }

    // 添加汇总行
    ui->tableWidget_monthlyReport->insertRow(row);
    QTableWidgetItem *item = new QTableWidgetItem("月总收入");
    item->setBackground(QColor(220, 220, 220));
    item->setFont(QFont("", -1, QFont::Bold));
    ui->tableWidget_monthlyReport->setItem(row, 0, item);
    ui->tableWidget_monthlyReport->setItem(row, 1, new QTableWidgetItem("--"));
    ui->tableWidget_monthlyReport->setItem(row, 2, new QTableWidgetItem("--"));
    ui->tableWidget_monthlyReport->setItem(row, 3, new QTableWidgetItem("--"));
    QTableWidgetItem *totalItem = new QTableWidgetItem(QString::number(monthlyTotal, 'f', 3));
    totalItem->setFont(QFont("", -1, QFont::Bold));
    totalItem->setBackground(QColor(220, 220, 220));
    ui->tableWidget_monthlyReport->setItem(row, 4, totalItem);

    // 更新状态栏显示
    statusBar()->showMessage(QString("%1月份总收入：¥%2").arg(month).arg(QString::number(monthlyTotal, 'f', 3)));

    // 更新分页控件状态
    updatePaginationControls("monthlyReport", currentMonthlyReportPage, totalPages);
}

// 生成生产统计报表（支持分页）
void MainWindow::onGenerateProductionStats()
{
    // 使用UI中存在的统计类型和班组选择控件
    QString statsType = ui->comboBox_statsType->currentText();
    QString team = ui->comboBox_statsDepartment->currentText();
    QString period = ui->comboBox_statsPeriod->currentText();
    
    // 根据统计周期确定日期范围
    QDate today = QDate::currentDate();
    QString startDate, endDate;

    if (period == "按日") {
        startDate = today.toString("yyyy-MM-dd");
        endDate = today.toString("yyyy-MM-dd");
    } else if (period == "按周") {
        startDate = today.addDays(-today.dayOfWeek() + 1).toString("yyyy-MM-dd"); // 本周一
        endDate = today.toString("yyyy-MM-dd");
    } else { // 按月
        // 获取用户选择的结束日期
        QDate selectedEndDate = ui->dateEdit_statsEndDate->date();
        // 开始日期为结束日期往前推一个月
        startDate = selectedEndDate.addMonths(-1).toString("yyyy-MM-dd");
        // 结束日期为用户选择的日期
        endDate = selectedEndDate.toString("yyyy-MM-dd");
    }

    // 数据验证
    if (startDate > endDate) {
        QMessageBox::warning(this, "数据验证失败", "开始日期不能晚于结束日期");
        return;
    }

    // 清空表格
    ui->tableWidget_factoryStats->setRowCount(0);

    // 构建查询语句 - 支持工序维度
    QString countQueryStr;
    QString dataQueryStr;
    
    if (statsType == "班组统计") {
        countQueryStr = "SELECT COUNT(*) FROM ("
                       "SELECT e.team "
                       "FROM production_v2 pv2 "
                       "JOIN employees e ON pv2.employee_id = e.id "
                       "JOIN toys t ON pv2.toy_id = t.id "
                       "JOIN processes p ON pv2.process_id = p.id "
                       "WHERE pv2.date BETWEEN ? AND ? ";

        dataQueryStr = "SELECT e.team AS group_name, "
                      "COUNT(DISTINCT pv2.employee_id) AS employee_count, "
                      "SUM(pv2.quantity) AS total_quantity, "
                      "SUM(pv2.subtotal) AS total_value, "
                      "COUNT(DISTINCT pv2.date) AS work_days, "
                      "ROUND(AVG(pv2.subtotal), 2) AS avg_daily_value "
                      "FROM production_v2 pv2 "
                      "JOIN employees e ON pv2.employee_id = e.id "
                      "JOIN toys t ON pv2.toy_id = t.id "
                      "JOIN processes p ON pv2.process_id = p.id "
                      "WHERE pv2.date BETWEEN ? AND ? ";

        if (team != "全部") {
            countQueryStr += "AND e.team = ? ";
            dataQueryStr += "AND e.team = ? ";
        }

        countQueryStr += "GROUP BY e.team) AS grouped_data";
        dataQueryStr += "GROUP BY e.team ORDER BY total_value DESC ";
    } else {
        // 全厂统计 - 按产品和工序维度
        // 如果是按月统计，我们按月份分组，确保每个月只显示一条记录
        if (period == "按月") {
            countQueryStr = "SELECT COUNT(*) FROM ("
                           "SELECT substr(pv2.date, 1, 7) "
                           "FROM production_v2 pv2 "
                           "JOIN toys t ON pv2.toy_id = t.id "
                           "JOIN processes p ON pv2.process_id = p.id "
                           "JOIN employees e ON pv2.employee_id = e.id "
                           "WHERE pv2.date BETWEEN ? AND ? ";

            dataQueryStr = "SELECT substr(pv2.date, 1, 7) AS month, "
                          "COUNT(DISTINCT pv2.employee_id) AS employee_count, "
                          "SUM(pv2.quantity) AS total_quantity, "
                          "SUM(pv2.subtotal) AS total_value, "
                          "ROUND(AVG(pv2.quantity), 2) AS avg_quantity "
                          "FROM production_v2 pv2 "
                          "JOIN toys t ON pv2.toy_id = t.id "
                          "JOIN processes p ON pv2.process_id = p.id "
                          "JOIN employees e ON pv2.employee_id = e.id "
                          "WHERE pv2.date BETWEEN ? AND ? ";

            if (team != "全部") {
                countQueryStr += "AND e.team = ? ";
                dataQueryStr += "AND e.team = ? ";
            }

            countQueryStr += "GROUP BY substr(pv2.date, 1, 7)) AS grouped_data";
            dataQueryStr += "GROUP BY substr(pv2.date, 1, 7) ORDER BY month ";
        } else {
            // 按日或按周统计保持原有逻辑
            countQueryStr = "SELECT COUNT(*) FROM ("
                           "SELECT t.name, p.name "
                           "FROM production_v2 pv2 "
                           "JOIN toys t ON pv2.toy_id = t.id "
                           "JOIN processes p ON pv2.process_id = p.id "
                           "JOIN employees e ON pv2.employee_id = e.id "
                           "WHERE pv2.date BETWEEN ? AND ? ";

            dataQueryStr = "SELECT t.name AS product_name, p.name AS process_name, "
                          "COUNT(DISTINCT pv2.employee_id) AS employee_count, "
                          "SUM(pv2.quantity) AS total_quantity, "
                          "SUM(pv2.subtotal) AS total_value, "
                          "ROUND(AVG(pv2.quantity), 2) AS avg_quantity "
                          "FROM production_v2 pv2 "
                          "JOIN toys t ON pv2.toy_id = t.id "
                          "JOIN processes p ON pv2.process_id = p.id "
                          "JOIN employees e ON pv2.employee_id = e.id "
                          "WHERE pv2.date BETWEEN ? AND ? ";

            if (team != "全部") {
                countQueryStr += "AND e.team = ? ";
                dataQueryStr += "AND e.team = ? ";
            }

            countQueryStr += "GROUP BY t.name, p.name) AS grouped_data";
            dataQueryStr += "GROUP BY t.name, p.name ORDER BY total_value DESC ";
        }
    }

    // 查询统计数据总数
    QSqlQuery countQuery;
    if (team != "全部") {
        countQuery.prepare(countQueryStr);
        countQuery.addBindValue(startDate);
        countQuery.addBindValue(endDate);
        countQuery.addBindValue(team);
    } else {
        countQuery.prepare(countQueryStr);
        countQuery.addBindValue(startDate);
        countQuery.addBindValue(endDate);
    }

    if (!executeQuery(countQuery, "查询生产统计数据总数失败", this)) {
        // 更新分页控件状态，即使查询失败也要更新
        updatePaginationControls("factoryStats", currentFactoryStatsPage, 1);
        return;
    }

    int totalRecords = 0;
    if (countQuery.next()) {
        totalRecords = countQuery.value(0).toInt();
    }
    totalFactoryStatsRecords = totalRecords;

    // 计算总页数
    int totalPages = (totalRecords + itemsPerPage - 1) / itemsPerPage;
    if (totalPages == 0) totalPages = 1;

    // 检查当前页码是否超出范围
    if (currentFactoryStatsPage >= totalPages && totalPages > 0) {
        currentFactoryStatsPage = totalPages - 1;
        if (currentFactoryStatsPage < 0) currentFactoryStatsPage = 0; // 确保不会为负数
    }

    // 计算偏移量
    int offset = currentFactoryStatsPage * itemsPerPage;

    // 查询统计数据 - 支持分页
    QSqlQuery query;
    dataQueryStr += "LIMIT ? OFFSET ?";
    
    if (team != "全部") {
        query.prepare(dataQueryStr);
        query.addBindValue(startDate);
        query.addBindValue(endDate);
        query.addBindValue(team);
        query.addBindValue(itemsPerPage);
        query.addBindValue(offset);
    } else {
        query.prepare(dataQueryStr);
        query.addBindValue(startDate);
        query.addBindValue(endDate);
        query.addBindValue(itemsPerPage);
        query.addBindValue(offset);
    }

    if (!executeQuery(query, "查询生产统计数据失败", this)) {
        // 更新分页控件状态，即使查询失败也要更新
        updatePaginationControls("factoryStats", currentFactoryStatsPage, totalPages);
        return;
    }

    // 填充表格 - 支持工序维度：日期/月份、玩具名称、工序名称、总产量、总产值、参与人数、操作
    bool hasData = false;
    int totalQuantity = 0;
    double totalValue = 0.0;
    int totalEmployees = 0;

    while (query.next()) {
        hasData = true;
        int row = ui->tableWidget_factoryStats->rowCount();
        ui->tableWidget_factoryStats->insertRow(row);

        if (period == "按月") {
            // 按月统计时的字段处理
            QString month = query.value(0).toString();
            int employeeCount = query.value(1).toInt();
            int quantity = query.value(2).toInt();
            double value = query.value(3).toDouble();
            
            ui->tableWidget_factoryStats->setItem(row, 0, new QTableWidgetItem(month)); // 月份
            ui->tableWidget_factoryStats->setItem(row, 1, new QTableWidgetItem("全厂统计")); // 统计类型
            ui->tableWidget_factoryStats->setItem(row, 2, new QTableWidgetItem(QString::number(quantity))); // 总产量
            ui->tableWidget_factoryStats->setItem(row, 3, new QTableWidgetItem(QString::number(value, 'f', 3))); // 总产值
            ui->tableWidget_factoryStats->setItem(row, 4, new QTableWidgetItem(QString::number(employeeCount))); // 参与人数
            ui->tableWidget_factoryStats->setItem(row, 5, new QTableWidgetItem("查看详情")); // 操作

            totalQuantity += quantity;
            totalValue += value;
            totalEmployees += employeeCount; // 累加参与人数而不是取最大值
        } else {
            // 按日或按周统计时的字段处理
            QString groupName = query.value(0).toString();
            QString processName = statsType == "班组统计" ? "" : query.value(1).toString();
            int employeeCount = query.value(2).toInt();
            int quantity = query.value(3).toInt();
            double value = query.value(4).toDouble();

            // 根据统计周期显示不同的日期/月份信息
            QString dateDisplay;
            if (period == "按周") {
                // 按周统计时显示周的起始日期
                dateDisplay = startDate;
            } else {
                // 按日统计时显示具体日期
                dateDisplay = startDate;
            }

            ui->tableWidget_factoryStats->setItem(row, 0, new QTableWidgetItem(dateDisplay)); // 日期/月份
            ui->tableWidget_factoryStats->setItem(row, 1, new QTableWidgetItem(groupName + (processName.isEmpty() ? "" : " - " + processName))); // 产品名称 - 工序名称
            ui->tableWidget_factoryStats->setItem(row, 2, new QTableWidgetItem(QString::number(quantity))); // 总产量
            ui->tableWidget_factoryStats->setItem(row, 3, new QTableWidgetItem(QString::number(value, 'f', 3))); // 总产值
            ui->tableWidget_factoryStats->setItem(row, 4, new QTableWidgetItem(QString::number(employeeCount))); // 参与人数
            ui->tableWidget_factoryStats->setItem(row, 5, new QTableWidgetItem("查看详情")); // 操作

            totalQuantity += quantity;
            totalValue += value;
            totalEmployees += employeeCount; // 累加参与人数而不是取最大值
        }
    }

    // 处理空结果
    if (!hasData) {
        QMessageBox::information(this, "提示", QString("在 %1 至 %2 期间没有找到生产统计记录")
                                 .arg(startDate).arg(endDate));
        statusBar()->showMessage("未找到统计数据");
        // 更新分页控件状态
        updatePaginationControls("factoryStats", currentFactoryStatsPage, totalPages);
        return;
    }

    // 添加汇总行
    int row = ui->tableWidget_factoryStats->rowCount();
    ui->tableWidget_factoryStats->insertRow(row);

    QTableWidgetItem *summaryItem = new QTableWidgetItem("总计");
    summaryItem->setBackground(QColor(220, 220, 220));
    summaryItem->setFont(QFont("", -1, QFont::Bold));
    ui->tableWidget_factoryStats->setItem(row, 0, summaryItem);
    ui->tableWidget_factoryStats->setItem(row, 1, new QTableWidgetItem("--"));

    QTableWidgetItem *totalQtyItem = new QTableWidgetItem(QString::number(totalQuantity));
    totalQtyItem->setFont(QFont("", -1, QFont::Bold));
    ui->tableWidget_factoryStats->setItem(row, 2, totalQtyItem);

    QTableWidgetItem *totalValueItem = new QTableWidgetItem(QString::number(totalValue, 'f', 3));
    totalValueItem->setFont(QFont("", -1, QFont::Bold));
    ui->tableWidget_factoryStats->setItem(row, 3, totalValueItem);

    ui->tableWidget_factoryStats->setItem(row, 4, new QTableWidgetItem(QString::number(totalEmployees)));
    ui->tableWidget_factoryStats->setItem(row, 5, new QTableWidgetItem("--"));

    // 更新状态栏显示
    statusBar()->showMessage(QString("统计期间：%1 至 %2，总产量：%3 件，总产值：￥%4，参与人数：%5 人")
                             .arg(startDate).arg(endDate)
                             .arg(totalQuantity)
                             .arg(QString::number(totalValue, 'f', 3))
                             .arg(totalEmployees));

    // 更新分页控件状态
    updatePaginationControls("factoryStats", currentFactoryStatsPage, totalPages);
}

// 计算工资
void MainWindow::onCalculatePayroll()
{
    QString month = ui->dateEdit_wageMonth->date().toString("yyyy-MM");
    QString monthStart = month + "-01";
    QString monthEnd = QDate::fromString(month + "-01", "yyyy-MM-dd").addMonths(1).addDays(-1).toString("yyyy-MM-dd");

    // 数据验证 - 检查日期范围是否有效
    QDate startDate = QDate::fromString(monthStart, "yyyy-MM-dd");
    QDate endDate = QDate::fromString(monthEnd, "yyyy-MM-dd");
    if (!startDate.isValid() || !endDate.isValid() || startDate > endDate) {
        QMessageBox::warning(this, "数据验证失败", "无效的日期范围");
        return;
    }

    // 如果选择了特定员工
    if (ui->comboBox_wageEmployee->currentIndex() >= 0) {
        int employeeId = ui->comboBox_wageEmployee->currentData().toInt();
        calculateSingleEmployeePayroll(employeeId, monthStart, monthEnd);
    } else {
        // 计算所有员工的工资
        calculateAllEmployeesPayroll(monthStart, monthEnd);
    }
}

// 生成工资条
void MainWindow::onGenerateWageSlip()
{
    // 获取选择的员工和月份
    int employeeId = ui->comboBox_wageEmployee->currentData().toInt();
    QString month = ui->dateEdit_wageMonth->date().toString("yyyy-MM");
    QString monthStart = month + "-01";
    QString monthEnd = QDate::fromString(month + "-01", "yyyy-MM-dd").addMonths(1).addDays(-1).toString("yyyy-MM-dd");

    // 数据验证
    if (employeeId <= 0) {
        QMessageBox::warning(this, "数据验证失败", "请先选择员工");
        return;
    }

    // 计算该员工的工资
    calculateSingleEmployeePayroll(employeeId, monthStart, monthEnd);
    
    QMessageBox::information(this, "成功", "工资条已生成");
}

// 导出工资明细
// 导出包含员工名称、玩具名称、工序名称、数量、单价、金额等详细信息的工资明细
void MainWindow::onExportWageDetails()
{
    // 确保有数据可以导出
    if (ui->tableWidget_wageDetails->rowCount() == 0) {
        QMessageBox::warning(this, "导出错误", "没有数据可以导出");
        return;
    }
    
    // 设置默认文件名
    QString defaultFileName = "工资明细_" + ui->dateEdit_wageMonth->date().toString("yyyyMM");
    
    // 打开文件保存对话框
    QString fileName = QFileDialog::getSaveFileName(this, "导出工资明细", defaultFileName,
                                                    "Excel文件 (*.xlsx);;CSV文件 (*.csv);;所有文件 (*)");
    
    if (fileName.isEmpty()) {
        return; // 用户取消了操作
    }
    
    // 根据文件扩展名确定导出格式
    if (fileName.endsWith(".xlsx", Qt::CaseInsensitive)) {
        // 导出为Excel格式
        exportTableWidgetToExcel(ui->tableWidget_wageDetails, fileName);
    } else {
        // 确保文件名以.csv结尾
        if (!fileName.endsWith(".csv", Qt::CaseInsensitive)) {
            fileName += ".csv";
        }
        // 导出为CSV格式
        exportTableWidget(ui->tableWidget_wageDetails, fileName);
    }
    
    QMessageBox::information(this, "导出完成", "工资明细已成功导出");
}

// 导出所有员工月工资
// 导出指定月份所有员工的详细工资信息，包含员工名称、玩具名称、工序名称、数量、单价、金额等
void MainWindow::onExportAllEmployeeWages()
{
    // 获取选择的月份
    QString month = ui->dateEdit_wageMonth->date().toString("yyyy-MM");
    QString monthStart = month + "-01";
    QString monthEnd = QDate::fromString(month + "-01", "yyyy-MM-dd").addMonths(1).addDays(-1).toString("yyyy-MM-dd");

    // 数据验证 - 检查日期范围是否有效
    QDate startDate = QDate::fromString(monthStart, "yyyy-MM-dd");
    QDate endDate = QDate::fromString(monthEnd, "yyyy-MM-dd");
    if (!startDate.isValid() || !endDate.isValid() || startDate > endDate) {
        QMessageBox::warning(this, "数据验证失败", "无效的日期范围");
        return;
    }

    // 查询所有员工的工资数据
    QSqlQuery query;
    query.prepare("SELECT e.name AS employee_name, t.name AS toy_name, p.name AS process_name, "
                  "pv2.quantity, pv2.piece_rate, pv2.subtotal "
                  "FROM production_v2 pv2 "
                  "JOIN employees e ON pv2.employee_id = e.id "
                  "JOIN toys t ON pv2.toy_id = t.id "
                  "JOIN processes p ON pv2.process_id = p.id "
                  "WHERE pv2.date BETWEEN ? AND ? "
                  "ORDER BY e.name, t.name, p.name");
    query.addBindValue(monthStart);
    query.addBindValue(monthEnd);

    if (!executeQuery(query, "查询所有员工工资数据失败", this)) {
        return;
    }

    // 设置默认文件名
    QString defaultFileName = "所有员工工资_" + ui->dateEdit_wageMonth->date().toString("yyyyMM");
    
    // 打开文件保存对话框
    QString fileName = QFileDialog::getSaveFileName(this, "导出所有员工工资", defaultFileName,
                                                    "Excel文件 (*.xlsx);;CSV文件 (*.csv);;所有文件 (*)");
    
    if (fileName.isEmpty()) {
        return; // 用户取消了操作
    }
    
    // 根据文件扩展名确定导出格式
    if (fileName.endsWith(".xlsx", Qt::CaseInsensitive)) {
        // 导出为Excel格式
        exportTableWidgetToExcel(ui->tableWidget_wageDetails, fileName);
    } else {
        // 确保文件名以.csv结尾
        if (!fileName.endsWith(".csv", Qt::CaseInsensitive)) {
            fileName += ".csv";
        }
        // 导出为CSV格式
        exportTableWidget(ui->tableWidget_wageDetails, fileName);
    }
    
    QMessageBox::information(this, "导出完成", "所有员工工资已成功导出");
}

// 显示生产统计详情
void MainWindow::showFactoryStatsDetails(const QString &productInfo, const QString &statsType, const QString &team, const QString &startDate, const QString &endDate)
{
    // 创建对话框显示详细信息
    QDialog *dialog = new QDialog(this);
    dialog->setWindowTitle("生产统计详情");
    dialog->resize(800, 600);
    
    QVBoxLayout *layout = new QVBoxLayout(dialog);
    
    // 标题
    QLabel *titleLabel = new QLabel(QString("统计期间：%1 至 %2").arg(startDate).arg(endDate));
    titleLabel->setStyleSheet("font-size: 16px; font-weight: bold; margin: 10px;");
    layout->addWidget(titleLabel);
    
    // 创建表格显示详细信息
    QTableWidget *detailsTable = new QTableWidget(dialog);
    detailsTable->setColumnCount(3);
    detailsTable->setHorizontalHeaderLabels(QStringList() << "员工姓名" << "班组" << "总金额");
    detailsTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    detailsTable->verticalHeader()->setDefaultSectionSize(30);
    layout->addWidget(detailsTable);
    
    // 查询详细数据 - 按员工分组统计总金额
    QSqlQuery query;
    
    QString queryStr = "SELECT e.name, e.team, SUM(pv2.subtotal) as total_amount "
                      "FROM production_v2 pv2 "
                      "JOIN employees e ON pv2.employee_id = e.id "
                      "WHERE pv2.date BETWEEN ? AND ? ";
    
    if (team != "全部") {
        queryStr += "AND e.team = ? ";
    }
    
    queryStr += "GROUP BY e.name, e.team "
                "ORDER BY total_amount DESC";
    
    query.prepare(queryStr);
    query.addBindValue(startDate);
    query.addBindValue(endDate);
    
    if (team != "全部") {
        query.addBindValue(team);
    }
    
    if (!executeQuery(query, "查询生产统计详情失败", this)) {
        delete dialog;
        return;
    }
    
    // 填充表格
    double totalValue = 0.0;
    int employeeCount = 0;
    
    while (query.next()) {
        int row = detailsTable->rowCount();
        detailsTable->insertRow(row);
        
        QString employeeName = query.value(0).toString();
        QString employeeTeam = query.value(1).toString();
        double totalAmount = query.value(2).toDouble();
        
        detailsTable->setItem(row, 0, new QTableWidgetItem(employeeName));
        detailsTable->setItem(row, 1, new QTableWidgetItem(employeeTeam));
        detailsTable->setItem(row, 2, new QTableWidgetItem(QString::number(totalAmount, 'f', 3)));
        
        totalValue += totalAmount;
        employeeCount++;
    }
    
    // 添加汇总行
    if (detailsTable->rowCount() > 0) {
        int row = detailsTable->rowCount();
        detailsTable->insertRow(row);
        
        QTableWidgetItem *summaryItem = new QTableWidgetItem("总计");
        summaryItem->setBackground(QColor(220, 220, 220));
        summaryItem->setFont(QFont("", -1, QFont::Bold));
        detailsTable->setItem(row, 0, summaryItem);
        detailsTable->setItem(row, 1, new QTableWidgetItem(QString("参与人数：%1人").arg(employeeCount)));
        QTableWidgetItem *totalValueItem = new QTableWidgetItem(QString::number(totalValue, 'f', 3));
        totalValueItem->setFont(QFont("", -1, QFont::Bold));
        detailsTable->setItem(row, 2, totalValueItem);
    }
    
    // 添加关闭按钮
    QPushButton *closeButton = new QPushButton("关闭");
    connect(closeButton, &QPushButton::clicked, dialog, &QDialog::close);
    layout->addWidget(closeButton, 0, Qt::AlignCenter);
    
    dialog->exec();
    delete dialog;
}

// 导出所有员工月工资
void MainWindow::exportAllEmployeeWages(const QString &monthStart, const QString &monthEnd, const QString &month)
{
    // 创建临时表格用于导出
    QTableWidget *tempTable = new QTableWidget(this);
    tempTable->setColumnCount(6);
    tempTable->setHorizontalHeaderLabels(QStringList() << "员工名称" << "玩具名称" << "工序名称" << "数量" << "单价" << "金额");

    // 查询所有员工的工资数据 - 按员工、玩具和工序维度分组显示
    QSqlQuery query;
    query.prepare("SELECT e.name, t.name as toy_name, p.name as process_name, "
                  "SUM(pv2.quantity) as total_qty, pv2.piece_rate, "
                  "SUM(pv2.subtotal) as total_amount "
                  "FROM production_v2 pv2 "
                  "JOIN employees e ON pv2.employee_id = e.id "
                  "JOIN toys t ON pv2.toy_id = t.id "
                  "JOIN processes p ON pv2.process_id = p.id "
                  "WHERE pv2.date BETWEEN ? AND ? "
                  "GROUP BY e.name, t.name, p.name, pv2.piece_rate "
                  "ORDER BY e.name, t.name, p.name");
    query.addBindValue(monthStart);
    query.addBindValue(monthEnd);

    if (!executeQuery(query, "查询所有员工工资数据失败", this)) {
        delete tempTable;
        return;
    }

    // 填充临时表格
    int row = 0;
    while (query.next()) {
        QString employeeName = query.value(0).toString();
        QString toyName = query.value(1).toString();
        QString processName = query.value(2).toString();
        int quantity = query.value(3).toInt();
        double pieceRate = query.value(4).toDouble();
        double amount = query.value(5).toDouble();

        tempTable->insertRow(row);
        tempTable->setItem(row, 0, new QTableWidgetItem(employeeName));     // 员工名称
        tempTable->setItem(row, 1, new QTableWidgetItem(toyName));          // 玩具名称
        tempTable->setItem(row, 2, new QTableWidgetItem(processName));      // 工序名称
        tempTable->setItem(row, 3, new QTableWidgetItem(QString::number(quantity)));       // 数量
        tempTable->setItem(row, 4, new QTableWidgetItem(QString::number(pieceRate, 'f', 3))); // 单价
        tempTable->setItem(row, 5, new QTableWidgetItem(QString::number(amount, 'f', 3)));    // 金额

        row++;
    }

    // 检查是否有数据
    if (row == 0) {
        QMessageBox::information(this, "提示", QString("在 %1 月份没有找到生产记录").arg(month));
        delete tempTable;
        return;
    }

    // 设置默认文件名
    QString defaultFileName = "所有员工工资明细_" + month + ".csv";
    
    // 打开文件保存对话框
    QString fileName = QFileDialog::getSaveFileName(this, "导出所有员工月工资", defaultFileName,
                                                    "CSV文件 (*.csv);;Excel文件 (*.xlsx);;所有文件 (*)");
    
    if (fileName.isEmpty()) {
        delete tempTable;
        return; // 用户取消了操作
    }
    
    // 根据文件扩展名确定导出格式
    if (fileName.endsWith(".xlsx", Qt::CaseInsensitive)) {
        // 导出为Excel格式（简化为CSV格式）
        QString csvFileName = fileName.left(fileName.lastIndexOf('.')) + ".csv";
        exportTableWidget(tempTable, csvFileName);
        QMessageBox::information(this, "导出完成", 
                                QString("文件已导出为CSV格式: %1\n注意：CSV文件可以在Excel中正常打开使用").arg(csvFileName));
    } else {
        // 确保文件名以.csv结尾
        if (!fileName.endsWith(".csv", Qt::CaseInsensitive)) {
            fileName += ".csv";
        }
        // 导出为CSV格式
        exportTableWidget(tempTable, fileName);
        QMessageBox::information(this, "导出完成", "所有员工月工资已成功导出到 " + fileName);
    }

    // 清理临时表格
    delete tempTable;
}

// 导出表格控件为Excel格式
void MainWindow::exportTableWidgetToExcel(QTableWidget *tableWidget, const QString &fileName)
{
    // 检查输入参数
    if (!tableWidget || fileName.isEmpty()) {
        QMessageBox::warning(this, "导出错误", "无效的参数");
        return;
    }
    
    // 简化实现：先导出为CSV格式，因为真正的Excel导出需要额外的库
    // 在实际应用中，可以使用QXlsx库来实现真正的Excel导出
    QString csvFileName = fileName;
    if (csvFileName.endsWith(".xlsx", Qt::CaseInsensitive)) {
        csvFileName = csvFileName.left(csvFileName.lastIndexOf('.')) + ".csv";
    }
    
    exportTableWidget(tableWidget, csvFileName);
    
    // 通知用户
    QMessageBox::information(this, "导出完成", 
                            QString("文件已导出为CSV格式: %1\n注意：CSV文件可以在Excel中正常打开使用").arg(csvFileName));
}

// 计算单个员工工资
void MainWindow::calculateSingleEmployeePayroll(int employeeId, const QString &monthStart, const QString &monthEnd)
{
    // 数据验证
    if (employeeId <= 0) {
        QMessageBox::warning(this, "数据验证失败", "无效的员工ID");
        return;
    }

    // 清空表格
    ui->tableWidget_wageDetails->setRowCount(0);

    // 查询工资数据 - 按玩具和工序维度分组显示
    QSqlQuery query;
    query.prepare("SELECT e.name, t.name as toy_name, p.name as process_name, "
                  "SUM(pv2.quantity) as total_qty, pv2.piece_rate, "
                  "SUM(pv2.subtotal) as total_amount "
                  "FROM production_v2 pv2 "
                  "JOIN employees e ON pv2.employee_id = e.id "
                  "JOIN toys t ON pv2.toy_id = t.id "
                  "JOIN processes p ON pv2.process_id = p.id "
                  "WHERE pv2.employee_id = ? AND pv2.date BETWEEN ? AND ? "
                  "GROUP BY e.name, t.name, p.name, pv2.piece_rate "
                  "ORDER BY t.name, p.name");
    query.addBindValue(employeeId);
    query.addBindValue(monthStart);
    query.addBindValue(monthEnd);

    if (!executeQuery(query, "计算工资失败", this)) {
        // 错误处理已在executeQuery中完成
        return;
    }

    // 填充表格和计算统计数据
    QString employeeName = "";
    int totalQuantity = 0;
    double totalAmount = 0.0;
    int row = 0;
    bool hasData = false;

    while (query.next()) {
        hasData = true;
        employeeName = query.value(0).toString();
        QString toyName = query.value(1).toString();
        QString processName = query.value(2).toString();
        int quantity = query.value(3).toInt();
        double pieceRate = query.value(4).toDouble();
        double amount = query.value(5).toDouble();

        ui->tableWidget_wageDetails->insertRow(row);
        ui->tableWidget_wageDetails->setItem(row, 0, new QTableWidgetItem(employeeName));  // 员工名称
        ui->tableWidget_wageDetails->setItem(row, 1, new QTableWidgetItem(toyName));       // 玩具名称
        ui->tableWidget_wageDetails->setItem(row, 2, new QTableWidgetItem(processName));   // 工序名称
        ui->tableWidget_wageDetails->setItem(row, 3, new QTableWidgetItem(QString::number(quantity)));      // 数量
        ui->tableWidget_wageDetails->setItem(row, 4, new QTableWidgetItem(QString::number(pieceRate, 'f', 3))); // 单价
        ui->tableWidget_wageDetails->setItem(row, 5, new QTableWidgetItem(QString::number(amount, 'f', 3)));    // 金额

        totalQuantity += quantity;
        totalAmount += amount;
        row++;
    }

    if (hasData) {
        // 更新统计信息
        ui->value_wageEmployeeName->setText(employeeName);
        ui->value_wagePeriod->setText(monthStart.left(7));
        ui->value_totalProduction->setText(QString::number(totalQuantity) + " 件");

        // 修复工资总额计算：只显示计件工资，不添加基本工资
        ui->value_wageAmount->setText("￥" + QString::number(totalAmount, 'f', 3));

        // 添加汇总行
        ui->tableWidget_wageDetails->insertRow(row);
        QTableWidgetItem *summaryItem = new QTableWidgetItem("合计");
        summaryItem->setBackground(QColor(220, 220, 220));
        summaryItem->setFont(QFont("", -1, QFont::Bold));
        ui->tableWidget_wageDetails->setItem(row, 0, summaryItem);
        ui->tableWidget_wageDetails->setItem(row, 1, new QTableWidgetItem("--"));
        ui->tableWidget_wageDetails->setItem(row, 2, new QTableWidgetItem("--"));
        ui->tableWidget_wageDetails->setItem(row, 3, new QTableWidgetItem(QString::number(totalQuantity)));
        ui->tableWidget_wageDetails->setItem(row, 4, new QTableWidgetItem("--"));
        QTableWidgetItem *totalAmountItem = new QTableWidgetItem(QString::number(totalAmount, 'f', 3));
        totalAmountItem->setFont(QFont("", -1, QFont::Bold));
        totalAmountItem->setBackground(QColor(220, 220, 220));
        ui->tableWidget_wageDetails->setItem(row, 5, totalAmountItem);
    } else {
        // 处理空结果
        QMessageBox::information(this, "提示", QString("在 %1 月份没有找到该员工的生产记录")
                                 .arg(monthStart.left(7)));

        // 重置统计信息
        ui->value_wageEmployeeName->setText("--");
        ui->value_wagePeriod->setText(monthStart.left(7));
        ui->value_totalProduction->setText("0 件");
        ui->value_wageAmount->setText("￥0.00");
    }
}

// 计算所有员工工资
void MainWindow::calculateAllEmployeesPayroll(const QString &monthStart, const QString &monthEnd)
{
    // 清空表格
    ui->tableWidget_wageDetails->setRowCount(0);

    // 查询工资数据 - 按员工分组显示汇总信息（支持工序维度）
    QSqlQuery query;
    query.prepare("SELECT e.name, e.employee_id, SUM(pv2.quantity) as total_qty, "
                  "SUM(pv2.subtotal) AS total_piece_wage "
                  "FROM production_v2 pv2 "
                  "JOIN employees e ON pv2.employee_id = e.id "
                  "JOIN toys t ON pv2.toy_id = t.id "
                  "JOIN processes p ON pv2.process_id = p.id "
                  "WHERE pv2.date BETWEEN ? AND ? "
                  "GROUP BY e.name, e.employee_id "
                  "ORDER BY e.name");
    query.addBindValue(monthStart);
    query.addBindValue(monthEnd);

    if (!executeQuery(query, "计算工资失败", this)) {
        // 错误处理已在executeQuery中完成
        return;
    }

    // 填充表格
    int row = 0;
    bool hasData = false;
    double grandTotalPieceWage = 0.0;
    int grandTotalQuantity = 0;

    while (query.next()) {
        hasData = true;
        QString employeeName = query.value(0).toString();
        QString employeeId = query.value(1).toString();
        int totalQuantity = query.value(2).toInt();
        double totalPieceWage = query.value(3).toDouble();

        // 基本工资（2000元） + 计件工资
        double baseSalary = 2000.0;
        double totalSalary = baseSalary + totalPieceWage;

        ui->tableWidget_wageDetails->insertRow(row);
        ui->tableWidget_wageDetails->setItem(row, 0, new QTableWidgetItem(employeeName + "(" + employeeId + ")"));  // 员工名称
        ui->tableWidget_wageDetails->setItem(row, 1, new QTableWidgetItem("--"));  // 玩具名称
        ui->tableWidget_wageDetails->setItem(row, 2, new QTableWidgetItem("--"));  // 工序名称
        ui->tableWidget_wageDetails->setItem(row, 3, new QTableWidgetItem(QString::number(totalQuantity)));  // 数量
        ui->tableWidget_wageDetails->setItem(row, 4, new QTableWidgetItem(QString::number(totalPieceWage, 'f', 3)));  // 单价
        ui->tableWidget_wageDetails->setItem(row, 5, new QTableWidgetItem(QString::number(totalSalary, 'f', 3)));  // 金额

        grandTotalQuantity += totalQuantity;
        grandTotalPieceWage += totalPieceWage;
        row++;
    }

    if (hasData) {
        // 添加汇总行
        ui->tableWidget_wageDetails->insertRow(row);
        QTableWidgetItem *summaryItem = new QTableWidgetItem("全员合计");
        summaryItem->setBackground(QColor(220, 220, 220));
        summaryItem->setFont(QFont("", -1, QFont::Bold));
        ui->tableWidget_wageDetails->setItem(row, 0, summaryItem);
        ui->tableWidget_wageDetails->setItem(row, 1, new QTableWidgetItem("--"));
        ui->tableWidget_wageDetails->setItem(row, 2, new QTableWidgetItem("--"));
        ui->tableWidget_wageDetails->setItem(row, 3, new QTableWidgetItem(QString::number(grandTotalQuantity)));
        QTableWidgetItem *totalPieceWageItem = new QTableWidgetItem(QString::number(grandTotalPieceWage, 'f', 3));
        totalPieceWageItem->setFont(QFont("", -1, QFont::Bold));
        ui->tableWidget_wageDetails->setItem(row, 4, totalPieceWageItem);

        // 计算总工资（修复：只计算计件工资总和）
        QTableWidgetItem *totalSalaryItem = new QTableWidgetItem(QString::number(grandTotalPieceWage, 'f', 3));
        totalSalaryItem->setFont(QFont("", -1, QFont::Bold));
        totalSalaryItem->setBackground(QColor(220, 220, 220));
        ui->tableWidget_wageDetails->setItem(row, 5, totalSalaryItem);

        // 更新统计信息
        ui->value_wageEmployeeName->setText(QString("全员工资统计（%1人）").arg(row));
        ui->value_wagePeriod->setText(monthStart.left(7));
        ui->value_totalProduction->setText(QString::number(grandTotalQuantity) + " 件");
        ui->value_wageAmount->setText("￥" + QString::number(grandTotalPieceWage, 'f', 3));
    } else {
        // 处理空结果
        QMessageBox::information(this, "提示", QString("在 %1 月份没有找到生产记录")
                                 .arg(monthStart.left(7)));

        // 重置统计信息
        ui->value_wageEmployeeName->setText("--");
        ui->value_wagePeriod->setText(monthStart.left(7));
        ui->value_totalProduction->setText("0 件");
        ui->value_wageAmount->setText("￥0.00");
    }
}

// 打印数据
void MainWindow::onPrintData()
{
    // 获取当前活动的标签页
    int currentTab = ui->mainTabWidget->currentIndex();
    QString title;
    QTableWidget *tableWidget = nullptr;

    switch (currentTab) {
    case 0: // 系统概览
        QMessageBox::information(this, "提示", "系统概览不支持打印");
        return;
    case 1: // 基础数据管理
        if (ui->basicDataSubTab->currentIndex() == 0) { // 员工管理
            title = "员工信息表";
            tableWidget = ui->tableWidget_employees;
        } else { // 玩具管理
            title = "玩具信息表";
            tableWidget = ui->tableWidget_products;
        }
        break;
    case 2: // 日常生产录入
        title = "生产记录表";
        tableWidget = ui->tableWidget_productionEntry;
        break;
    case 3: // 数据查询与统计
        if (ui->querySubTab->currentIndex() == 0) { // 员工日报表
            title = "员工日报表";
            tableWidget = ui->tableWidget_dailyReport;
        } else if (ui->querySubTab->currentIndex() == 1) { // 员工月报表
            title = "员工月报表";
            tableWidget = ui->tableWidget_monthlyReport;
        } else { // 生产统计
            title = "生产统计表";
            tableWidget = ui->tableWidget_factoryStats;
        }
        break;
    case 4: // 工资核算
        title = "工资表";
        tableWidget = ui->tableWidget_wageDetails;
        break;
    default:
        QMessageBox::information(this, "提示", "当前页面不支持打印");
        return;
    }

    if (tableWidget) {
        printTableWidget(tableWidget, title);
    }
}

// 打印预览
void MainWindow::onPrintPreview()
{
    // 获取当前活动的标签页
    int currentTab = ui->mainTabWidget->currentIndex();
    QString title;
    QTableWidget *tableWidget = nullptr;

    switch (currentTab) {
    case 0: // 系统概览
        QMessageBox::information(this, "提示", "系统概览不支持打印预览");
        return;
    case 1: // 基础数据管理
        if (ui->basicDataSubTab->currentIndex() == 0) { // 员工管理
            title = "员工信息表";
            tableWidget = ui->tableWidget_employees;
        } else { // 玩具管理
            title = "玩具信息表";
            tableWidget = ui->tableWidget_products;
        }
        break;
    case 2: // 日常生产录入
        title = "生产记录表";
        tableWidget = ui->tableWidget_productionEntry;
        break;
    case 3: // 数据查询与统计
        if (ui->querySubTab->currentIndex() == 0) { // 员工日报表
            title = "员工日报表";
            tableWidget = ui->tableWidget_dailyReport;
        } else if (ui->querySubTab->currentIndex() == 1) { // 员工月报表
            title = "员工月报表";
            tableWidget = ui->tableWidget_monthlyReport;
        } else { // 生产统计
            title = "生产统计表";
            tableWidget = ui->tableWidget_factoryStats;
        }
        break;
    case 4: // 工资核算
        title = "工资表";
        tableWidget = ui->tableWidget_wageDetails;
        break;
    default:
        QMessageBox::information(this, "提示", "当前页面不支持打印预览");
        return;
    }

    if (!tableWidget) {
        return;
    }

    // 生成HTML内容
    QString htmlContent = generateHtmlTable(tableWidget, title);

    // 创建打印机对象
    QPrinter printer(QPrinter::ScreenResolution); // 使用屏幕分辨率以提高预览性能
    printer.setDocName(title);

    // 创建临时的 QTextDocument 用于检查内容是否有效
    QTextDocument tempDocument;
    tempDocument.setHtml(htmlContent);

    // 检查文档是否有效
    if (tempDocument.isEmpty()) {
        QMessageBox::warning(this, "预览错误", "无法生成预览内容");
        return;
    }

    // 检查打印机是否有效
    if (!printer.isValid()) {
        QMessageBox::warning(this, "预览错误", "打印机设备无效，请检查打印机设置");
        return;
    }

    // 尝试创建打印预览对话框
    try {
        QPrintPreviewDialog preview(&printer, this);

        connect(&preview, &QPrintPreviewDialog::paintRequested, [=](QPrinter *previewPrinter) {
            // 在 paintRequested 信号中再次检查打印机是否有效
            if (!previewPrinter || !previewPrinter->isValid()) {
                QMessageBox::warning(this, "预览错误", "打印机设备无效，请检查打印机设置");
                return;
            }

            // 创建文档并打印
            QTextDocument document;
            document.setHtml(htmlContent);

            // 检查文档是否有效
            if (document.isEmpty()) {
                QMessageBox::warning(this, "预览错误", "无法生成预览内容");
                return;
            }

            // 在打印前检查设备是否准备好
            if (!previewPrinter->printerName().isEmpty()) {
                // 尝试设置输出格式
                previewPrinter->setOutputFormat(QPrinter::NativeFormat);
            }

            // 执行打印
            document.print(previewPrinter);
        });

        preview.exec();
    } catch (const std::exception& e) {
        QMessageBox::warning(this, "预览错误", QString("无法创建打印预览：%1").arg(e.what()));
    } catch (...) {
        QMessageBox::warning(this, "预览错误", "无法创建打印预览，请检查打印机设置");
    }
}

// 打印表格控件
void MainWindow::printTableWidget(QTableWidget *tableWidget, const QString &title)
{
    // 生成HTML内容
    QString htmlContent = generateHtmlTable(tableWidget, title);

    // 创建打印机对象
    QPrinter printer(QPrinter::HighResolution);
    printer.setDocName(title);

    // 检查系统中是否有可用的打印机
    QList<QPrinterInfo> availablePrinters = QPrinterInfo::availablePrinters();
    if (availablePrinters.isEmpty()) {
        // 如果没有可用打印机，使用默认打印机（即使可能无效）
        printer.setPrinterName(QPrinterInfo::defaultPrinter().printerName());
    } else {
        // 使用第一个可用的打印机
        printer.setPrinterName(availablePrinters.first().printerName());
    }

    // 检查打印机是否有效
    if (!printer.isValid()) {
        QMessageBox::warning(this, "打印错误", "未找到有效的打印机，请检查打印机设置");
        return;
    }

    // 创建文本文档
    QTextDocument document;
    document.setHtml(htmlContent);

    // 检查文档是否有效
    if (document.isEmpty()) {
        QMessageBox::warning(this, "打印错误", "无法生成打印内容");
        return;
    }

    // 在打印前检查设备是否准备好
    if (!printer.printerName().isEmpty()) {
        // 尝试设置输出格式
        printer.setOutputFormat(QPrinter::NativeFormat);
    }

    // 打印文档
    try {
        document.print(&printer);
        QMessageBox::information(this, "成功", "打印完成");
    } catch (const std::exception& e) {
        QMessageBox::warning(this, "打印错误", QString("打印失败：%1").arg(e.what()));
    } catch (...) {
        QMessageBox::warning(this, "打印错误", "打印失败，请检查打印机设置");
    }
}

// 生成HTML表格
QString MainWindow::generateHtmlTable(QTableWidget *tableWidget, const QString &title)
{
    // 检查输入参数
    if (!tableWidget) {
        return QString(); // 返回空字符串表示错误
    }

    // 检查表格是否为空
    if (tableWidget->rowCount() == 0 && tableWidget->columnCount() == 0) {
        return QString(); // 返回空字符串表示错误
    }

    QString html = "<html><head><meta charset=\"utf-8\"><style>";
    html += "table { border-collapse: collapse; width: 100%; }";
    html += "th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }";
    html += "th { background-color: #f2f2f2; font-weight: bold; }";
    html += "h1 { text-align: center; }";
    html += "</style></head><body>";

    html += "<h1>" + title + "</h1>";
    html += "<table>";

    // 添加表头
    html += "<tr>";
    for (int col = 0; col < tableWidget->columnCount(); col++) {
        QTableWidgetItem *headerItem = tableWidget->horizontalHeaderItem(col);
        QString headerText = headerItem ? headerItem->text() : QString("列%1").arg(col + 1);
        html += "<th>" + headerText + "</th>";
    }
    html += "</tr>";

    // 添加数据行
    for (int row = 0; row < tableWidget->rowCount(); row++) {
        html += "<tr>";
        for (int col = 0; col < tableWidget->columnCount(); col++) {
            QString cellText;

            // 对于单元格部件，需要特殊处理
            if (tableWidget->cellWidget(row, col)) {
                QComboBox *comboBox = qobject_cast<QComboBox*>(tableWidget->cellWidget(row, col));
                if (comboBox) {
                    cellText = comboBox->currentText();
                }
            } else if (tableWidget->item(row, col)) {
                cellText = tableWidget->item(row, col)->text();
            }

            html += "<td>" + cellText + "</td>";
        }
        html += "</tr>";
    }

    html += "</table>";
    html += "</body></html>";

    return html;
}

// 导出数据
void MainWindow::onExportData()
{
    // 获取当前活动的标签页
    int currentTab = ui->mainTabWidget->currentIndex();
    QString fileName;
    QTableWidget *tableWidget = nullptr;

    switch (currentTab) {
    case 0: // 系统概览
        QMessageBox::information(this, "提示", "系统概览不支持导出数据");
        return;
    case 1: // 基础数据管理
        if (ui->basicDataSubTab->currentIndex() == 0) { // 员工管理
            fileName = "员工信息.csv";
            tableWidget = ui->tableWidget_employees;
        } else { // 玩具管理
            fileName = "玩具信息.csv";
            tableWidget = ui->tableWidget_products;
        }
        break;
    case 2: // 日常生产录入
        fileName = "生产记录.csv";
        tableWidget = ui->tableWidget_productionEntry;
        break;
    case 3: // 数据查询与统计
        if (ui->querySubTab->currentIndex() == 0) { // 员工日报表
            fileName = "员工日报表.csv";
            tableWidget = ui->tableWidget_dailyReport;
        } else if (ui->querySubTab->currentIndex() == 1) { // 员工月报表
            fileName = "员工月报表.csv";
            tableWidget = ui->tableWidget_monthlyReport;
        } else { // 生产统计
            fileName = "生产统计.csv";
            tableWidget = ui->tableWidget_factoryStats;
        }
        break;
    case 4: // 工资核算
        fileName = "工资表.csv";
        tableWidget = ui->tableWidget_wageDetails;
        break;
    default:
        QMessageBox::information(this, "提示", "当前页面不支持导出数据");
        return;
    }

    if (tableWidget) {
        exportTableWidget(tableWidget, fileName);
    }
}

// 导出表格控件
void MainWindow::exportTableWidget(QTableWidget *tableWidget, const QString &fileName)
{
    // 打开文件
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::warning(this, "导出错误", "无法打开文件进行写入");
        return;
    }

    // 创建文本流
    QTextStream out(&file);

    // 写入表头
    for (int col = 0; col < tableWidget->columnCount(); col++) {
        if (col > 0) {
            out << ",";
        }
        // 对表头进行转义处理，防止包含逗号等特殊字符
        QString headerText = tableWidget->horizontalHeaderItem(col)->text();
        if (headerText.contains(",") || headerText.contains("\"") || headerText.contains("\n")) {
            headerText = "\"" + headerText.replace("\"", "\"\"") + "\"";
        }
        out << headerText;
    }
    out << "\n";

    // 写入数据行
    for (int row = 0; row < tableWidget->rowCount(); row++) {
        for (int col = 0; col < tableWidget->columnCount(); col++) {
            QString cellText;

            // 对于单元格部件，需要特殊处理
            if (tableWidget->cellWidget(row, col)) {
                QComboBox *comboBox = qobject_cast<QComboBox*>(tableWidget->cellWidget(row, col));
                if (comboBox) {
                    cellText = comboBox->currentText();
                }
            } else if (tableWidget->item(row, col)) {
                cellText = tableWidget->item(row, col)->text();
            }

            // 对单元格内容进行转义处理，防止包含逗号等特殊字符
            if (cellText.contains(",") || cellText.contains("\"") || cellText.contains("\n")) {
                cellText = "\"" + cellText.replace("\"", "\"\"") + "\"";
            }

            if (col > 0) {
                out << ",";
            }
            out << cellText;
        }
        out << "\n";
    }

    // 关闭文件
    file.close();

    QMessageBox::information(this, "成功", "数据已成功导出到 " + fileName);
}

// 备份数据
void MainWindow::onBackupData()
{
    // 关闭数据库连接
    db.close();

    // 选择备份路径
    QString timestamp = QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss");
    QString fileName = "toy_factory_backup_" + timestamp + ".db";
    QString filePath = QFileDialog::getSaveFileName(this, "备份数据",
                                                   QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/" + fileName,
                                                   "数据库文件 (*.db);;所有文件 (*.*)");

    if (filePath.isEmpty()) {
        db.open(); // 重新打开数据库
        return;
    }

    // 复制数据库文件
    QFile::copy("toy_factory.db", filePath);

    // 重新打开数据库
    db.open();

    QMessageBox::information(this, "成功", "数据备份成功\n备份文件: " + filePath);
}

// 新增函数实现

// 统一的添加/更新员工函数（现在使用弹框模式）
void MainWindow::onAddOrUpdateEmployee()
{
    // 由于已改为弹框模式，这个函数现在只需要调用对应的添加函数
    // 所有的添加和编辑都通过弹框进行，不再使用表单输入
    onAddEmployee();
}

// 搜索员工
void MainWindow::onSearchEmployee()
{
    QString searchText = ui->lineEdit_searchEmployee->text().trimmed();

    if (searchText.isEmpty()) {
        // 如果搜索框为空，显示所有员工
        loadEmployees();
        return;
    }

    ui->tableWidget_employees->setRowCount(0);

    QSqlQuery query;
    query.prepare("SELECT employee_id, name, team, hire_date, contact, status FROM employees WHERE employee_id LIKE ? OR name LIKE ? OR team LIKE ?");
    QString likePattern = "%" + searchText + "%";
    query.addBindValue(likePattern);
    query.addBindValue(likePattern);
    query.addBindValue(likePattern);

    if (!executeQuery(query, "搜索员工失败", this)) {
        return;
    }

    int row = 0;
    while (query.next()) {
        ui->tableWidget_employees->insertRow(row);
        ui->tableWidget_employees->setItem(row, 0, new QTableWidgetItem(query.value(0).toString()));
        ui->tableWidget_employees->setItem(row, 1, new QTableWidgetItem(query.value(1).toString()));
        ui->tableWidget_employees->setItem(row, 2, new QTableWidgetItem(query.value(2).toString()));
        ui->tableWidget_employees->setItem(row, 3, new QTableWidgetItem(query.value(3).toString()));
        ui->tableWidget_employees->setItem(row, 4, new QTableWidgetItem(query.value(4).toString()));
        ui->tableWidget_employees->setItem(row, 5, new QTableWidgetItem(query.value(5).toString()));

        // 添加编辑按钮
        QPushButton *editBtn = new QPushButton("编辑");
        editBtn->setStyleSheet("QPushButton { background-color: #3498db; color: white; border: none; padding: 4px 8px; border-radius: 2px; }");
        connect(editBtn, &QPushButton::clicked, [this, row]() {
            ui->tableWidget_employees->selectRow(row);
            onEditEmployee();
        });
        ui->tableWidget_employees->setCellWidget(row, 6, editBtn);

        row++;
    }

    statusBar()->showMessage(QString("搜索到 %1 名员工").arg(row));
}

// 员工选择变化
void MainWindow::onEmployeeSelectionChanged()
{
    // 可以在这里添加员工选择变化的处理逻辑
}

// 搜索产品
void MainWindow::onSearchProduct()
{
    QString searchText = ui->lineEdit_searchProduct->text().trimmed();

    if (searchText.isEmpty()) {
        loadToys();
        return;
    }

    ui->tableWidget_products->setRowCount(0);

    QSqlQuery query;
    query.prepare("SELECT toy_id, name, description, piece_rate FROM toys WHERE toy_id LIKE ? OR name LIKE ? OR description LIKE ?");
    QString likePattern = "%" + searchText + "%";
    query.addBindValue(likePattern);
    query.addBindValue(likePattern);
    query.addBindValue(likePattern);

    if (!executeQuery(query, "搜索产品失败", this)) {
        return;
    }

    int row = 0;
    while (query.next()) {
        ui->tableWidget_products->insertRow(row);
        ui->tableWidget_products->setItem(row, 0, new QTableWidgetItem(query.value(0).toString()));
        ui->tableWidget_products->setItem(row, 1, new QTableWidgetItem(query.value(1).toString()));
        ui->tableWidget_products->setItem(row, 2, new QTableWidgetItem(query.value(2).toString()));
        ui->tableWidget_products->setItem(row, 3, new QTableWidgetItem(QString::number(query.value(3).toDouble(), 'f', 3)));
        row++;
    }

    statusBar()->showMessage(QString("搜索到 %1 个产品").arg(row));
}

// 产品选择变化
void MainWindow::onProductSelectionChanged()
{
    // 可以在这里添加产品选择变化的处理逻辑
}

// 添加班组
void MainWindow::onAddDepartment()
{
    QString departmentName = ui->lineEdit_departmentName->text().trimmed();

    if (departmentName.isEmpty()) {
        QMessageBox::warning(this, "输入错误", "请输入班组名称");
        ui->lineEdit_departmentName->setFocus();
        return;
    }

    // 检查班组是否已存在
    QSqlQuery checkQuery;
    checkQuery.prepare("SELECT COUNT(*) FROM departments WHERE name = ?");
    checkQuery.addBindValue(departmentName);

    if (executeQuery(checkQuery, "检查班组是否存在失败", this) && checkQuery.next()) {
        if (checkQuery.value(0).toInt() > 0) {
            QMessageBox::warning(this, "输入错误", "班组已存在");
            return;
        }
    }

    QSqlQuery query;
    query.prepare("INSERT INTO departments (name) VALUES (?)");
    query.addBindValue(departmentName);

    if (executeQuery(query, "添加班组失败", this)) {
        QMessageBox::information(this, "成功", "班组添加成功");
        ui->lineEdit_departmentName->clear();

        // 使用分页加载班组数据
        loadDepartmentsWithPagination(currentDeptPage);
        loadEmployeeComboBoxes();
    }
}

// 删除班组
void MainWindow::onDeleteDepartment()
{
    // 获取所有选中的行
    QList<QTableWidgetItem*> selectedItems = ui->tableWidget_departments->selectedItems();
    if (selectedItems.isEmpty()) {
        QMessageBox::warning(this, "警告", "请先选择要删除的班组");
        return;
    }

    // 获取选中行的唯一行号
    QSet<int> selectedRows;
    for (QTableWidgetItem* item : selectedItems) {
        selectedRows.insert(item->row());
    }

    // 构建确认信息
    QString confirmMessage;
    if (selectedRows.size() == 1) {
        int row = *selectedRows.begin();
        QString departmentName = ui->tableWidget_departments->item(row, 1)->text();
        confirmMessage = "确定要删除班组 " + departmentName + " 吗？";
    } else {
        confirmMessage = QString("确定要删除选中的 %1 个班组吗？").arg(selectedRows.size());
    }

    if (QMessageBox::question(this, "确认删除", confirmMessage) == QMessageBox::Yes) {
        bool success = true;
        int deletedCount = 0;
        
        // 开始事务
        if (!beginTransaction(db, "删除班组时开启事务失败", this)) {
            return;
        }

        // 遍历选中的行并删除
        for (int row : selectedRows) {
            QString departmentName = ui->tableWidget_departments->item(row, 1)->text();
            
            QSqlQuery query;
            query.prepare("DELETE FROM departments WHERE name = ?");
            query.addBindValue(departmentName);

            if (!executeQuery(query, "删除班组失败", this)) {
                success = false;
                break;
            }
            deletedCount++;
        }

        if (success) {
            // 提交事务
            if (db.commit()) {
                QMessageBox::information(this, "成功", QString("成功删除 %1 个班组").arg(deletedCount));
                loadDepartmentsWithPagination(currentDeptPage);
                loadEmployeeComboBoxes();
            } else {
                db.rollback();
                QMessageBox::critical(this, "错误", "提交事务失败: " + db.lastError().text());
            }
        } else {
            db.rollback();
            QMessageBox::critical(this, "错误", "删除班组失败");
        }
    }
}

// 加载班组数据
void MainWindow::loadDepartments()
{
    ui->tableWidget_departments->setRowCount(0);

    QSqlQuery query("SELECT id, name FROM departments ORDER BY name");
    int row = 0;
    while (query.next()) {
        ui->tableWidget_departments->insertRow(row);
        ui->tableWidget_departments->setItem(row, 0, new QTableWidgetItem(query.value(0).toString()));
        ui->tableWidget_departments->setItem(row, 1, new QTableWidgetItem(query.value(1).toString()));

        row++;
    }
}

// 统一的添加/更新玩具函数（现在使用弹框模式）
void MainWindow::onAddOrUpdateToy()
{
    // 由于已改为弹框模式，这个函数现在只需要调用对应的添加或编辑函数
    // 具体的添加和编辑逻辑在 onAddToy() 和 onEditToy() 中实现
    if (ui->pushButton_addProduct->text() == "更新玩具") {
        onEditToy();
    } else {
        onAddToy();
    }
}

// 更新生产行小计 - 优化版本
void MainWindow::updateRowSubtotal(int row)
{
    if (row < 0 || row >= ui->tableWidget_productionEntry->rowCount()) {
        return;
    }

    QTableWidgetItem *priceItem = ui->tableWidget_productionEntry->item(row, 2);
    QTableWidgetItem *quantityItem = ui->tableWidget_productionEntry->item(row, 3);

    if (!priceItem || !quantityItem) {
        return;
    }

    // 获取单价和数量
    bool priceOk, quantityOk;
    double price = priceItem->text().toDouble(&priceOk);
    int quantity = quantityItem->text().toInt(&quantityOk);

    if (!priceOk || !quantityOk || quantity < 0) {
        // 如果数据无效，设置小计为0
        QTableWidgetItem *subtotalItem = ui->tableWidget_productionEntry->item(row, 4);
        if (subtotalItem) {
            subtotalItem->setText("0.00");
        } else {
            QTableWidgetItem *newSubtotalItem = new QTableWidgetItem("0.00");
            newSubtotalItem->setFlags(newSubtotalItem->flags() & ~Qt::ItemIsEditable); // 不可编辑
            ui->tableWidget_productionEntry->setItem(row, 4, newSubtotalItem);
        }
        updateProductionTotal();
        return;
    }

    // 计算小计
    double subtotal = price * quantity;

    // 更新小计显示
    QTableWidgetItem *subtotalItem = ui->tableWidget_productionEntry->item(row, 4);
    if (subtotalItem) {
        subtotalItem->setText(QString::number(subtotal, 'f', 3));
    } else {
        QTableWidgetItem *newSubtotalItem = new QTableWidgetItem(QString::number(subtotal, 'f', 3));
        newSubtotalItem->setFlags(newSubtotalItem->flags() & ~Qt::ItemIsEditable); // 不可编辑
        ui->tableWidget_productionEntry->setItem(row, 4, newSubtotalItem);
    }

    // 更新总计
    updateProductionTotal();
}

// 更新生产总计 - 优化版本
void MainWindow::updateProductionTotal()
{
    double total = 0.0;
    int totalQuantity = 0;
    int validRows = 0;

    for (int row = 0; row < ui->tableWidget_productionEntry->rowCount(); row++) {
        QTableWidgetItem *subtotalItem = ui->tableWidget_productionEntry->item(row, 4);
        QTableWidgetItem *quantityItem = ui->tableWidget_productionEntry->item(row, 3);

        if (subtotalItem && quantityItem) {
            bool subtotalOk, quantityOk;
            double subtotal = subtotalItem->text().toDouble(&subtotalOk);
            int quantity = quantityItem->text().toInt(&quantityOk);

            if (subtotalOk && quantityOk && quantity > 0) {
                total += subtotal;
                totalQuantity += quantity;
                validRows++;
            }
        }
    }

    // 在状态栏显示总计信息
    if (validRows > 0) {
        statusBar()->showMessage(QString("当前生产记录：%1行，总数量 %2 件，总金额 ￥%3")
                                 .arg(validRows)
                                 .arg(totalQuantity)
                                 .arg(QString::number(total, 'f', 3)));
    } else {
        statusBar()->showMessage("当前无有效生产记录");
    }
}

// 为指定玩具更新工序列表
void MainWindow::updateProcessListForToy(QComboBox *toyComboBox, QComboBox *processComboBox, int toyId)
{
    if (!toyComboBox || !processComboBox) {
        return;
    }
    
    // 如果选择了"请选择玩具产品"选项，则清空工序列表
    if (toyId <= 0) {
        processComboBox->clear();
        processComboBox->addItem("请先选择玩具产品", -1);
        return;
    }

    processComboBox->clear();

    // 查询该玩具关联的工序
    QSqlQuery processQuery;
    processQuery.prepare("SELECT p.id, p.process_id, p.name, p.piece_rate "
                        "FROM processes p "
                        "JOIN toy_processes tp ON tp.process_id = p.id "
                        "WHERE tp.toy_id = ? AND p.status = '启用' "
                        "ORDER BY tp.sequence_order, p.process_id");
    processQuery.addBindValue(toyId);

    if (executeQuery(processQuery, "查询玩具工序失败", this)) {
        while (processQuery.next()) {
            int procId = processQuery.value(0).toInt();
            QString processCode = processQuery.value(1).toString();
            QString processName = processQuery.value(2).toString();
            double pieceRate = processQuery.value(3).toDouble();

            QString displayText = QString("%1 - %2 (¥%3)").arg(processCode).arg(processName).arg(pieceRate, 0, 'f', 3);
            processComboBox->addItem(displayText, procId);
        }
    }

    if (processComboBox->count() == 0) {
        processComboBox->addItem("该玩具无关联工序", -1);
    }
}

// 将玩具数据加载到ComboBox中
void MainWindow::loadToyDataIntoComboBox(QComboBox *comboBox)
{
    if (!comboBox) {
        return;
    }
    
    comboBox->clear();
    
    QSqlQuery toyQuery("SELECT id, toy_id, name FROM toys ORDER BY name");
    if (executeQuery(toyQuery, "查询玩具数据失败", this)) {
        comboBox->addItem("请选择玩具产品", -1);
        while (toyQuery.next()) {
            int id = toyQuery.value(0).toInt();
            QString toyId = toyQuery.value(1).toString();
            QString name = toyQuery.value(2).toString();
            QString displayText = QString("%1 - %2").arg(toyId).arg(name);
            comboBox->addItem(displayText, id);
        }
    }
}

// 连接工序选择变化信号，更新计件单价
void MainWindow::connectProcessSelectionChanged(QComboBox *processComboBox)
{
    if (!processComboBox) {
        return;
    }
    
    // 连接工序选择变化信号，更新计件单价
    connect(processComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), 
            this, &MainWindow::onProcessSelectionChanged);
}

// 工序选择变化时的处理槽函数
void MainWindow::onProcessSelectionChanged(int index)
{
    // 获取发送信号的工序下拉框
    QComboBox *processComboBox = qobject_cast<QComboBox*>(sender());
    if (!processComboBox || index < 0) {
        return;
    }
    
    // 获取工序ID
    int processId = processComboBox->currentData().toInt();
    if (processId <= 0) {
        return;
    }
    
    // 查找该下拉框所在的行
    int row = -1;
    for (int i = 0; i < ui->tableWidget_productionEntry->rowCount(); i++) {
        if (ui->tableWidget_productionEntry->cellWidget(i, 1) == processComboBox) {
            row = i;
            break;
        }
    }
    
    if (row < 0) {
        return;
    }
    
    // 查询工序的计件单价
    QSqlQuery query;
    query.prepare("SELECT piece_rate FROM processes WHERE id = ?");
    query.addBindValue(processId);
    
    double pieceRate = 0.0;
    if (executeQuery(query, "查询工序计件单价失败", this) && query.next()) {
        pieceRate = query.value(0).toDouble();
    }
    
    // 更新计件单价显示
    QTableWidgetItem *priceItem = ui->tableWidget_productionEntry->item(row, 2);
    if (priceItem) {
        priceItem->setText(QString::number(pieceRate, 'f', 3));
    }
    
    // 更新小计金额
    QTableWidgetItem *quantityItem = ui->tableWidget_productionEntry->item(row, 3);
    QTableWidgetItem *subtotalItem = ui->tableWidget_productionEntry->item(row, 4);
    
    if (quantityItem && subtotalItem) {
        int quantity = quantityItem->text().toInt();
        double subtotal = quantity * pieceRate;
        subtotalItem->setText(QString::number(subtotal, 'f', 3));
        
        // 更新总计
        updateProductionTotal();
    }
}

// 显示生产详情
// 修改函数签名以支持工序维度查询
void MainWindow::showProductionDetails(int employeeId, const QString &toyName, const QString &processName, const QString &startDate, const QString &endDate)
{
    QMessageBox detailBox;
    detailBox.setWindowTitle("生产详情");
    detailBox.setIcon(QMessageBox::Information);

    // 查询支持工序维度的生产详情
    QSqlQuery query;
    if (processName.isEmpty() || processName == "无工序") {
        // 查询旧版本表（无工序信息）
        query.prepare("SELECT p.date, p.quantity, t.piece_rate, (p.quantity * t.piece_rate) AS amount "
                      "FROM production p "
                      "JOIN toys t ON p.toy_id = t.id "
                      "WHERE p.employee_id = ? AND t.name = ? AND p.date BETWEEN ? AND ? "
                      "ORDER BY p.date");
        query.addBindValue(employeeId);
        query.addBindValue(toyName);
        query.addBindValue(startDate);
        query.addBindValue(endDate);
    } else {
        // 查询新版本表（包含工序信息）
        query.prepare("SELECT pv2.date, pv2.quantity, pv2.piece_rate, pv2.subtotal AS amount "
                      "FROM production_v2 pv2 "
                      "JOIN toys t ON pv2.toy_id = t.id "
                      "JOIN processes p ON pv2.process_id = p.id "
                      "WHERE pv2.employee_id = ? AND t.name = ? AND p.name = ? AND pv2.date BETWEEN ? AND ? "
                      "ORDER BY pv2.date");
        query.addBindValue(employeeId);
        query.addBindValue(toyName);
        query.addBindValue(processName);
        query.addBindValue(startDate);
        query.addBindValue(endDate);
    }

    QString detailText = QString("玩具：%1").arg(toyName);
    if (!processName.isEmpty() && processName != "无工序") {
        detailText += QString("\n工序：%1").arg(processName);
    }
    detailText += "\n\n";

    if (executeQuery(query, "查询生产详情失败", this)) {
        detailText += "日期\t\t数量\t单价\t金额\n";
        detailText += "---------------------------------\n";

        double totalAmount = 0;
        int totalQuantity = 0;

        while (query.next()) {
            QString date = query.value(0).toString();
            int quantity = query.value(1).toInt();
            double price = query.value(2).toDouble();
            double amount = query.value(3).toDouble();

            detailText += QString("%1\t%2\t￥%3\t￥%4\n")
                         .arg(date)
                         .arg(quantity)
                         .arg(QString::number(price, 'f', 3))
                         .arg(QString::number(amount, 'f', 3));

            totalAmount += amount;
            totalQuantity += quantity;
        }

        detailText += "---------------------------------\n";
        detailText += QString("合计\t\t%1\t\t￥%2")
                     .arg(totalQuantity)
                     .arg(QString::number(totalAmount, 'f', 3));
    }

    detailBox.setText(detailText);
    detailBox.exec();
}

// 保持原有的函数签名以兼容旧代码
void MainWindow::showProductionDetails(int employeeId, const QString &toyName, const QString &startDate, const QString &endDate)
{
    // 调用新的函数，传入空的工序名称
    showProductionDetails(employeeId, toyName, "", startDate, endDate);
}

// 重置员工搜索
void MainWindow::onResetEmployee()
{
    ui->lineEdit_searchEmployee->clear();
    loadEmployees(); // 重新加载所有员工
}

// 重置产品搜索
void MainWindow::onResetProduct()
{
    ui->lineEdit_searchProduct->clear();
    loadToys(); // 重新加载所有产品
}

// 重置日报表查询
void MainWindow::onResetDailyReport()
{
    // 重置员工选择
    if (ui->comboBox_dailyReportEmployee->count() > 0) {
        ui->comboBox_dailyReportEmployee->setCurrentIndex(0);
    }

    // 重置日期范围（近一个月）
    ui->dateEdit_startDate->setDate(QDate::currentDate().addDays(-30));
    ui->dateEdit_endDate->setDate(QDate::currentDate());

    // 清空表格
    ui->tableWidget_dailyReport->setRowCount(0);

    // 更新状态栏
    statusBar()->showMessage("日报表查询已重置");
}

// 重置月报表查询
void MainWindow::onResetMonthlyReport()
{
    // 重置员工选择
    if (ui->comboBox_monthlyReportEmployee->count() > 0) {
        ui->comboBox_monthlyReportEmployee->setCurrentIndex(0);
    }

    // 重置为当前月份
    ui->dateEdit_month->setDate(QDate::currentDate());

    // 清空表格
    ui->tableWidget_monthlyReport->setRowCount(0);

    // 更新状态栏
    statusBar()->showMessage("月报表查询已重置");
}

// 重置生产统计查询
void MainWindow::onResetFactoryStats()
{
    // 重置统计类型
    ui->comboBox_statsType->setCurrentIndex(0);

    // 重置班组选择
    if (ui->comboBox_statsDepartment->count() > 0) {
        ui->comboBox_statsDepartment->setCurrentIndex(0);
    }

    // 重置统计周期
    ui->comboBox_statsPeriod->setCurrentIndex(0);

    // 清空表格
    ui->tableWidget_factoryStats->setRowCount(0);

    // 更新状态栏
    statusBar()->showMessage("生产统计查询已重置");
}

// 重置工资查询
void MainWindow::onResetWage()
{
    // 重置员工选择
    if (ui->comboBox_wageEmployee->count() > 0) {
        ui->comboBox_wageEmployee->setCurrentIndex(0);
    }

    // 重置为当前月份
    ui->dateEdit_wageMonth->setDate(QDate::currentDate());

    // 清空表格
    ui->tableWidget_wageDetails->setRowCount(0);

    // 重置工资汇总显示
    ui->value_wageEmployeeName->setText("--");
    ui->value_wagePeriod->setText("--");
    ui->value_totalProduction->setText("0 件");
    ui->value_wageAmount->setText("￥0.00");

    // 更新状态栏
    statusBar()->showMessage("工资查询已重置");
}

// 分页功能实现 - 员工分页
void MainWindow::onEmployeePageChanged(int page)
{
    currentEmployeePage = page;
    loadEmployeesWithPagination(page);
}

// 分页功能实现 - 玩具分页
void MainWindow::onToyPageChanged(int page)
{
    currentToyPage = page;
    loadToysWithPagination(page);
}

// 分页功能实现 - 班组分页
void MainWindow::onDepartmentPageChanged(int page)
{
    currentDeptPage = page;
    loadDepartmentsWithPagination(page);
}

// 分页功能实现 - 生产记录分页
void MainWindow::onProductionPageChanged(int page)
{
    currentProductionPage = page;
    // 生产录入不需要分页显示，这里预留接口
}

// 带分页的员工数据加载
void MainWindow::loadEmployeesWithPagination(int page)
{
    ui->tableWidget_employees->setRowCount(0);

    // 计算偏移量
    int offset = page * itemsPerPage;

    // 查询总记录数
    QSqlQuery countQuery("SELECT COUNT(*) FROM employees");
    int totalRecords = 0;
    if (executeQuery(countQuery, "查询员工总数失败", this) && countQuery.next()) {
        totalRecords = countQuery.value(0).toInt();
    }
    totalEmployeeRecords = totalRecords; // 保存总记录数

    // 计算总页数
    int totalPages = (totalRecords + itemsPerPage - 1) / itemsPerPage;

    // 查询当前页数据
    QSqlQuery query;
    query.prepare("SELECT employee_id, name, team, hire_date, contact, status FROM employees LIMIT ? OFFSET ?");
    query.addBindValue(itemsPerPage);
    query.addBindValue(offset);

    if (executeQuery(query, "查询员工分页数据失败", this)) {
        int row = 0;
        while (query.next()) {
            ui->tableWidget_employees->insertRow(row);
            ui->tableWidget_employees->setItem(row, 0, new QTableWidgetItem(query.value(0).toString()));
            ui->tableWidget_employees->setItem(row, 1, new QTableWidgetItem(query.value(1).toString()));
            ui->tableWidget_employees->setItem(row, 2, new QTableWidgetItem(query.value(2).toString()));
            ui->tableWidget_employees->setItem(row, 3, new QTableWidgetItem(query.value(3).toString()));
            ui->tableWidget_employees->setItem(row, 4, new QTableWidgetItem(query.value(4).toString()));
            ui->tableWidget_employees->setItem(row, 5, new QTableWidgetItem(query.value(5).toString()));

            // 添加操作按钮
            QPushButton *editBtn = new QPushButton("编辑");
            editBtn->setStyleSheet("QPushButton { background-color: #3498db; color: white; border: none; padding: 4px 8px; border-radius: 2px; }");
            connect(editBtn, &QPushButton::clicked, [this, row]() {
                ui->tableWidget_employees->selectRow(row);
                onEditEmployee();
            });
            ui->tableWidget_employees->setCellWidget(row, 6, editBtn);

            row++;
        }
    }

    // 更新分页控件状态
    updatePaginationControls("employee", page, totalPages);
}

// 带分页的玩具数据加载
void MainWindow::loadToysWithPagination(int page)
{
    ui->tableWidget_products->setRowCount(0);

    // 计算偏移量
    int offset = page * itemsPerPage;

    // 查询总记录数
    QSqlQuery countQuery("SELECT COUNT(*) FROM toys");
    int totalRecords = 0;
    if (executeQuery(countQuery, "查询玩具总数失败", this) && countQuery.next()) {
        totalRecords = countQuery.value(0).toInt();
    }
    totalToyRecords = totalRecords; // 保存总记录数

    // 计算总页数
    int totalPages = (totalRecords + itemsPerPage - 1) / itemsPerPage;

    // 查询当前页数据
    QSqlQuery query;
    query.prepare("SELECT toy_id, name, description, piece_rate FROM toys LIMIT ? OFFSET ?");
    query.addBindValue(itemsPerPage);
    query.addBindValue(offset);

    if (executeQuery(query, "查询玩具分页数据失败", this)) {
        int row = 0;
        while (query.next()) {
            ui->tableWidget_products->insertRow(row);
            ui->tableWidget_products->setItem(row, 0, new QTableWidgetItem(query.value(0).toString()));
            ui->tableWidget_products->setItem(row, 1, new QTableWidgetItem(query.value(1).toString()));
            ui->tableWidget_products->setItem(row, 2, new QTableWidgetItem(query.value(2).toString()));
            ui->tableWidget_products->setItem(row, 3, new QTableWidgetItem(QString::number(query.value(3).toDouble(), 'f', 3)));
            row++;
        }
    }

    // 更新分页控件状态
    updatePaginationControls("toy", page, totalPages);
}

// 带分页的班组数据加载
void MainWindow::loadDepartmentsWithPagination(int page)
{
    ui->tableWidget_departments->setRowCount(0);

    // 计算偏移量
    int offset = page * itemsPerPage;

    // 查询总记录数
    QSqlQuery countQuery("SELECT COUNT(*) FROM departments");
    int totalRecords = 0;
    if (executeQuery(countQuery, "查询班组总数失败", this) && countQuery.next()) {
        totalRecords = countQuery.value(0).toInt();
    }
    totalDeptRecords = totalRecords; // 保存总记录数

    // 计算总页数
    int totalPages = (totalRecords + itemsPerPage - 1) / itemsPerPage;

    // 查询当前页数据
    QSqlQuery query;
    query.prepare("SELECT id, name FROM departments LIMIT ? OFFSET ?");
    query.addBindValue(itemsPerPage);
    query.addBindValue(offset);

    if (executeQuery(query, "查询班组分页数据失败", this)) {
        int row = 0;
        while (query.next()) {
            ui->tableWidget_departments->insertRow(row);
            ui->tableWidget_departments->setItem(row, 0, new QTableWidgetItem(query.value(0).toString()));
            ui->tableWidget_departments->setItem(row, 1, new QTableWidgetItem(query.value(1).toString()));
            row++;
        }
    }

    // 更新分页控件状态
    updatePaginationControls("department", page, totalPages);
}

// 更新分页控件状态
void MainWindow::updatePaginationControls(const QString &tableName, int currentPage, int totalPages)
{
    // 在状态栏显示分页信息
    QString pageInfo = QString("%1 - 第%2页，共%3页，每页%4条记录")
                      .arg(tableName == "employee" ? "员工列表" :
                           tableName == "toy" ? "玩具列表" :
                           tableName == "recentActivityTable" ? "最近生产记录" :
                           tableName == "process" ? "工序列表" :
                           tableName == "dailyReport" ? "员工日报表" :
                           tableName == "monthlyReport" ? "员工月报表" : "全厂/班组产量统计")
                      .arg(currentPage + 1)
                      .arg(totalPages)
                      .arg(itemsPerPage);

    statusBar()->showMessage(pageInfo);

    // 更新最近生产记录的分页控件
    if (tableName == "recentActivityTable") {
        // 更新页面信息标签
        QString pageText = QString("%1/%2")
                          .arg(currentPage + 1)
                          .arg(totalPages);
        ui->label_pageInfoRecentActivity->setText(pageText);
        
        // 更新按钮状态
        ui->pushButton_firstPageRecentActivity->setEnabled(currentPage > 0);
        ui->pushButton_prevPageRecentActivity->setEnabled(currentPage > 0);
        ui->pushButton_nextPageRecentActivity->setEnabled(currentPage < totalPages - 1);
        ui->pushButton_lastPageRecentActivity->setEnabled(currentPage < totalPages - 1);
    }
    // 更新员工管理的分页控件
    else if (tableName == "employee") {
        // 更新页面信息标签
        QString pageText = QString("%1/%2")
                          .arg(currentPage + 1)
                          .arg(totalPages);
        ui->label_pageInfoEmployee->setText(pageText);
        
        // 更新按钮状态
        ui->pushButton_firstPageEmployee->setEnabled(currentPage > 0);
        ui->pushButton_prevPageEmployee->setEnabled(currentPage > 0);
        ui->pushButton_nextPageEmployee->setEnabled(currentPage < totalPages - 1);
        ui->pushButton_lastPageEmployee->setEnabled(currentPage < totalPages - 1);
    }
    // 更新产品管理的分页控件
    else if (tableName == "toy") {
        // 更新页面信息标签
        QString pageText = QString("%1/%2")
                          .arg(currentPage + 1)
                          .arg(totalPages);
        ui->label_pageInfoProduct->setText(pageText);
        
        // 更新按钮状态
        ui->pushButton_firstPageProduct->setEnabled(currentPage > 0);
        ui->pushButton_prevPageProduct->setEnabled(currentPage > 0);
        ui->pushButton_nextPageProduct->setEnabled(currentPage < totalPages - 1);
        ui->pushButton_lastPageProduct->setEnabled(currentPage < totalPages - 1);
    }
    // 更新班组管理的分页控件
    else if (tableName == "department") {
        // 更新页面信息标签
        QString pageText = QString("%1/%2")
                          .arg(currentPage + 1)
                          .arg(totalPages);
        ui->label_pageInfoDepartment->setText(pageText);
        
        // 更新按钮状态
        ui->pushButton_firstPageDepartment->setEnabled(currentPage > 0);
        ui->pushButton_prevPageDepartment->setEnabled(currentPage > 0);
        ui->pushButton_nextPageDepartment->setEnabled(currentPage < totalPages - 1);
        ui->pushButton_lastPageDepartment->setEnabled(currentPage < totalPages - 1);
    }
    // 更新工序管理的分页控件
    else if (tableName == "process") {
        // 更新页面信息标签
        QString pageText = QString("%1/%2")
                          .arg(currentPage + 1)
                          .arg(totalPages);
        
        // 直接使用成员变量更新工序分页控件
        if (label_pageInfoProcess) {
            label_pageInfoProcess->setText(pageText);
        }
        
        // 更新按钮状态
        if (pushButton_firstPageProcess) pushButton_firstPageProcess->setEnabled(currentPage > 0);
        if (pushButton_prevPageProcess) pushButton_prevPageProcess->setEnabled(currentPage > 0);
        if (pushButton_nextPageProcess) pushButton_nextPageProcess->setEnabled(currentPage < totalPages - 1);
        if (pushButton_lastPageProcess) pushButton_lastPageProcess->setEnabled(currentPage < totalPages - 1);
    }
    // 更新员工日报表的分页控件
    else if (tableName == "dailyReport") {
        // 更新页面信息标签
        QString pageText = QString("%1/%2")
                          .arg(currentPage + 1)
                          .arg(totalPages);
        
        // 直接使用成员变量更新员工日报表分页控件
        if (label_pageInfoDailyReport) {
            label_pageInfoDailyReport->setText(pageText);
        }
        
        // 更新按钮状态
        if (pushButton_firstPageDailyReport) pushButton_firstPageDailyReport->setEnabled(currentPage > 0);
        if (pushButton_prevPageDailyReport) pushButton_prevPageDailyReport->setEnabled(currentPage > 0);
        if (pushButton_nextPageDailyReport) pushButton_nextPageDailyReport->setEnabled(currentPage < totalPages - 1);
        if (pushButton_lastPageDailyReport) pushButton_lastPageDailyReport->setEnabled(currentPage < totalPages - 1);
    }
    // 更新员工月报表的分页控件
    else if (tableName == "monthlyReport") {
        // 更新页面信息标签
        QString pageText = QString("%1/%2")
                          .arg(currentPage + 1)
                          .arg(totalPages);
        
        // 直接使用成员变量更新员工月报表分页控件
        if (label_pageInfoMonthlyReport) {
            label_pageInfoMonthlyReport->setText(pageText);
        }
        
        // 更新按钮状态
        if (pushButton_firstPageMonthlyReport) pushButton_firstPageMonthlyReport->setEnabled(currentPage > 0);
        if (pushButton_prevPageMonthlyReport) pushButton_prevPageMonthlyReport->setEnabled(currentPage > 0);
        if (pushButton_nextPageMonthlyReport) pushButton_nextPageMonthlyReport->setEnabled(currentPage < totalPages - 1);
        if (pushButton_lastPageMonthlyReport) pushButton_lastPageMonthlyReport->setEnabled(currentPage < totalPages - 1);
    }
    // 更新全厂/班组产量统计的分页控件
    else if (tableName == "factoryStats") {
        // 更新页面信息标签
        QString pageText = QString("%1/%2")
                          .arg(currentPage + 1)
                          .arg(totalPages);
        
        // 直接使用成员变量更新全厂/班组产量统计分页控件
        if (label_pageInfoFactoryStats) {
            label_pageInfoFactoryStats->setText(pageText);
        }
        
        // 更新按钮状态
        if (pushButton_firstPageFactoryStats) pushButton_firstPageFactoryStats->setEnabled(currentPage > 0);
        if (pushButton_prevPageFactoryStats) pushButton_prevPageFactoryStats->setEnabled(currentPage > 0);
        if (pushButton_nextPageFactoryStats) pushButton_nextPageFactoryStats->setEnabled(currentPage < totalPages - 1);
        if (pushButton_lastPageFactoryStats) pushButton_lastPageFactoryStats->setEnabled(currentPage < totalPages - 1);
    }
}

// 带分页的员工日报表数据加载
void MainWindow::loadDailyReportWithPagination(int page)
{
    // 员工日报表不需要分页显示，这里预留接口
    // 实际应用中，如果数据量很大，可以考虑实现分页功能
}

// 带分页的员工月报表数据加载
void MainWindow::loadMonthlyReportWithPagination(int page)
{
    // 员工月报表不需要分页显示，这里预留接口
    // 实际应用中，如果数据量很大，可以考虑实现分页功能
}

// 带分页的全厂/班组产量统计数据加载
void MainWindow::loadFactoryStatsWithPagination(int page)
{
    // 全厂/班组产量统计不需要分页显示，这里预留接口
    // 实际应用中，如果数据量很大，可以考虑实现分页功能
}

// 系统设置槽函数 - 新增
void MainWindow::onSystemSettings()
{
    // 创建密码验证对话框
    PasswordDialog *passwordDialog = new PasswordDialog(this);
    
    // 如果密码验证通过，显示系统设置对话框
    if (passwordDialog->exec() == QDialog::Accepted && passwordDialog->isAuthenticated()) {
        showSystemSettings();
    }
    
    // 清理对话框
    delete passwordDialog;
}

// 显示系统设置对话框 - 新增
void MainWindow::showSystemSettings()
{
    // 创建系统设置对话框
    SystemSettingsDialog *settingsDialog = new SystemSettingsDialog(this);
    
    // 显示对话框
    settingsDialog->exec();
    
    // 清理对话框
    delete settingsDialog;
}
